24 Commits

Author SHA1 Message Date
Bartłomiej Janczak
34e4339c7c Release v1.6.0: Google Safe Browsing integration, VPN/Proxy/Bot filtering, and Visitor World Map widget 2026-06-02 17:56:16 +02:00
Bartłomiej Janczak
e847328b9b UX: Dynamically show/hide Developer API Keys section based on REST API enable state 2026-06-02 13:22:35 +02:00
Bartłomiej Janczak
911e98a2e3 Release v1.5.1: Rest API toggle, webhook fault tolerance, time-boundary aggregation fix, pixel loading UI, and resolveRedirectUrl targeting rules alignment 2026-06-02 13:17:42 +02:00
Bartłomiej Janczak
bdef0b6687 feat: add api_enabled on/off toggle in settings + update README for v1.5 2026-06-02 11:10:10 +02:00
Bartłomiej Janczak
e0b7e3f28c feat: add social retargeting pixels, developer REST API, and webhooks system 2026-06-02 09:44:53 +02:00
Bartłomiej Janczak
e29c3ef24e fix: resolve real-time visit limits under counter buffering and enforce rotation weight constraints 2026-06-02 09:27:06 +02:00
Bartłomiej Janczak
b1416fbe86 chore: exclude art and tests folders from composer distribution using .gitattributes 2026-06-02 09:18:03 +02:00
Bartłomiej Janczak
59e4fc0e6b v1.4.0: Add validity ranges, visit limit counters, custom redirects, and reactive controls 2026-06-02 09:16:47 +02:00
Bartłomiej Janczak
0e371ad139 Fix database compatibility: use database-agnostic boolean check in case statement for PostgreSQL 2026-06-02 07:55:22 +02:00
Bartłomiej Janczak
e5437dd0a6 Audit fixes: device targeting, query index optimizations, translation gaps, rate-limiting, and path consistency 2026-06-02 07:51:45 +02:00
Bartłomiej Janczak
65a1b126df feat: global overview widget, optimized cache, CSS asset docs
- Add ShortUrlGlobalOverview StatsOverviewWidget with split cache strategy:
  link counts cached forever (invalidated on create/delete), click stats
  with short TTL (geo_ip.stats_cache_ttl config)
- Fix visited_at column in ShortUrlVisit queries (was created_at)
- Disable Livewire polling (pollingInterval = null)
- Add cache invalidation for global overview in ShortUrl::booted()
- Rewrite README asset section: user-facing install instructions clarified,
  post-autoload-dump tip added, developer recompile notes separated
2026-06-01 18:59:17 +02:00
Bartłomiej Janczak
f0d76ff03b fix: memory-safe aggregation via chunking + allow 0 retention days
- Replace ->get() with ->chunk(1000) in AggregateAndPruneVisitsCommand
  to avoid loading entire day's visits into PHP RAM (critical at scale)
- Stats are now accumulated incrementally via a hash-keyed array,
  unique visits counted via ip_hash deduplication key
- Fix pruning_retention_days minValue(1) → minValue(0) in Settings form;
  0 was documented to disable pruning but form validation blocked it
2026-06-01 14:20:43 +02:00
Bartłomiej Janczak
eda4794cac feat: v1.2.0 — password protection, warning pages, smart targeting, rate limiting, daily stats aggregation
- Add password-protected links with session-based unlock flow
- Add redirect warning (interstitial) pages before external URLs
- Add smart targeting rules: device-based, country/geo, A/B weighted rotation
- Add configurable per-IP rate limiting with 429 + Retry-After headers
- Add daily stats aggregation & log pruning (short-url:aggregate-and-prune)
- Add IncrementVisitJob as queue-based counter buffering fallback
- Add ShortUrlDailyStats model with JSON stat columns per day
- Add two new migrations: targeting/security fields, daily_stats table
- Add password-prompt.blade.php and warning.blade.php views
- Extend Settings GUI with Performance & Security tab (aggregation + rate limiting)
- Extend ShortUrlForm with Targeting & Security section
- Add POST route for password form submission (was GET-only → 405)
- Replace enum(device_type) with string(20) for cross-DB compatibility
- Remove ->after() MySQL-only hints from ALTER TABLE migrations
- Fix aggregation test: use whereDate() instead of assertDatabaseHas for date column
- Extend en/pl translations for all new features
- Expand README.md with full v1.2.0 documentation (476 lines)
2026-06-01 13:54:13 +02:00
Bartłomiej Janczak
69f6cef31b feat: Add UTM parameters, interactive date range filter, cleaned referrer domains, and visitor city tracking to analytics 2026-06-01 13:24:02 +02:00
Bartłomiej Janczak
2ab85dd264 fix: Import ShortUrlResource in ShortUrlsTable to resolve class not found error 2026-06-01 13:10:01 +02:00
Bartłomiej Janczak
f518d4dae9 chore: Update license badge URL in README 2026-06-01 13:07:55 +02:00
Bartłomiej Janczak
bdbe9b2ffd v1.2.0: Added counter buffering (write-back caching), CDN trust headers toggle, full UI localization, dynamic Filament routes, and high-concurrency fixes 2026-06-01 13:05:48 +02:00
Bartłomiej Janczak
c842096a22 style: fix qr-designer spacing when Tailwind helper classes are unbuilt 2026-06-01 12:35:49 +02:00
Bartłomiej Janczak
7035e5b84b Update README.md 2026-06-01 12:35:17 +02:00
Bartłomiej Janczak
3b97ad3d00 add LICENSE file 2026-06-01 12:17:49 +02:00
Bartłomiej Janczak
a5f5afa198 docs: improve README layout with centered 3D logo and Shields.io status badges 2026-06-01 12:08:14 +02:00
Bartłomiej Janczak
429896d8e3 docs: complete README documentation for all settings, builders, env parameters, and bot filtering 2026-06-01 12:06:04 +02:00
Bartłomiej Janczak
985aa43155 docs: update README with navigationLabel and navigationIcon, fix composer require username 2026-06-01 10:28:39 +02:00
Bartłomiej Janczak
cd9a4a1620 feat: add navigationLabel() and navigationIcon() to plugin API 2026-06-01 10:27:02 +02:00
63 changed files with 6324 additions and 444 deletions

4
.gitattributes vendored Normal file
View File

@@ -0,0 +1,4 @@
/art export-ignore
/tests export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Bartek Janczak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

768
README.md
View File

@@ -1,22 +1,61 @@
# Filament Short URL
<p align="center">
<img src="https://cdn3d.iconscout.com/3d/premium/thumb/url-3d-icon-png-download-9292351.png" width="180" alt="Filament Short URL Logo">
</p>
A professional, high-performance **Short URL Manager** plugin for [Filament v5](https://filamentphp.com). Built from scratch with cutting-edge practices, proxy resistance, offline Geo-IP engines, and zero external shortening API dependencies.
<h1 align="center">Filament Short URL</h1>
<p align="center">
<a href="https://packagist.org/packages/janczakb/filament-short-url"><img src="https://img.shields.io/packagist/v/janczakb/filament-short-url.svg?style=flat-square" alt="Latest Version"></a>
<a href="https://github.com/janczakb/filament-short-url/blob/main/LICENSE"><img src="https://img.shields.io/github/license/janczakb/filament-short-url.svg?style=flat-square" alt="License"></a>
<a href="https://packagist.org/packages/janczakb/filament-short-url"><img src="https://img.shields.io/packagist/dt/janczakb/filament-short-url.svg?style=flat-square" alt="Total Downloads"></a>
<a href="https://github.com/janczakb/filament-short-url/stargazers"><img src="https://img.shields.io/github/stars/janczakb/filament-short-url.svg?style=flat-square" alt="GitHub Stars"></a>
<a href="https://github.com/janczakb/filament-short-url/issues"><img src="https://img.shields.io/github/issues/janczakb/filament-short-url.svg?style=flat-square" alt="GitHub Issues"></a>
<a href="https://github.com/janczakb/filament-short-url/actions"><img src="https://img.shields.io/badge/tests-passing-success.svg?style=flat-square" alt="Tests"></a>
</p>
A professional, high-performance **Short URL Manager** plugin for [Filament v5](https://filamentphp.com). Built from scratch with cutting-edge practices, proxy resistance, offline Geo-IP engines, enterprise-grade smart targeting, and zero external shortening API dependencies.
## Screenshots
<p align="center">
<table align="center" style="border-collapse: collapse; border: none;">
<tr style="border: none;">
<td width="50%" style="border: none; padding: 5px;"><img src="art/1.png" alt="Dashboard Stats" style="border-radius: 8px;"></td>
<td width="50%" style="border: none; padding: 5px;"><img src="art/2.png" alt="Short URL Creation Form" style="border-radius: 8px;"></td>
</tr>
<tr style="border: none;">
<td width="50%" style="border: none; padding: 5px;"><img src="art/3.png" alt="Targeting and Rules" style="border-radius: 8px;"></td>
<td width="50%" style="border: none; padding: 5px;"><img src="art/4.png" alt="Interactive Settings Panel" style="border-radius: 8px;"></td>
</tr>
</table>
</p>
---
## Features
- 🔗 **Short URL Generation**custom or auto-generated collision-free base62 keys.
- 🌍 **Multiple Geo-IP Drivers** — offline detection using local MaxMind databases, edge-provided CDN headers (Cloudflare, CloudFront), or fallback API integration.
- 📈 **Real-Time Statistics Dashboard** — sortable log of visits with cached aggregate performance metrics (browsers, devices, OS, referers, country maps, timeline charts).
- 🎨 **QR Code Designer** — live design canvas (sizes, dot styles, gradient configurations, and background transparency triggers) with instant SVG download.
- **Ultra-Fast Redirects** — redirects resolve in milliseconds; analytical tasks and GA4 payloads are processed asynchronously via Laravel Queue jobs.
- 🎯 **Google Analytics 4 Measurement Protocol** — native server-side event tracking, bypassing browser-side AdBlockers completely.
- ⚙️ **Reactive UTM Campaign Builder** — double-way synchronized UTM builder panel inside the Filament form, syncing seamlessly with destination URLs in real-time.
- 🔒 **Single-Use & Expirable Links** — automatically deactivates links after a single visit or at a specified date/time.
- ➡️ **Query Parameter Forwarding** — dynamically appends incoming client query parameters (e.g. ad clicks, discount codes) to the final destination URL.
- 🛠 **Dedicated Settings Interface** — full administrator control panel inside Filament to manage routing, Geo-IP, and GA4 credentials without editing `.env` files.
- 💻 **Fluent Developer Builder** — static Model builder patterns and trace tagging support.
- 🔗 **Short URL Generation**Create custom links or let the system auto-generate collision-free Base62 keys.
- 🌍 **Multiple Geo-IP Drivers** High-speed offline detection using local MaxMind databases, edge-provided CDN headers (Cloudflare, CloudFront, generic), or fallback API integration.
- 🗺️ **Visitor World Map Widget** — Interactive SVG world map on the link statistics dashboard showcasing the geographical distribution of visitor clicks with hover details.
- 📈 **Real-Time Statistics Dashboard** — Track visits in real-time with cached aggregate metrics (countries, devices, browsers, operating systems, referrers, traffic charts, and maps).
- 🛡️ **VPN, Proxy & Bot Filtering** — Exclude VPNs, proxies, Tor exit nodes, and automated bot clicks from your analytics to keep visitor statistics accurate.
- 🔍 **Google Safe Browsing Integration** — Automatically verify target URLs on creation/edit to block malicious, phishing, malware, or social engineering links.
- 🎨 **SVG QR Code Designer** — Built-in interactive design canvas in Filament to customize dot styles, margins, gradient coloring, and background transparency with instant SVG download.
- **Ultra-Fast Redirects** — Redirections resolve in milliseconds. Analytical tasks, event dispatching, and GA4 payloads are processed asynchronously via Laravel Queue jobs.
- 🎯 **Google Analytics 4 server-side tracking** — Native integration with the GA4 Measurement Protocol to bypass client-side AdBlockers completely.
- **Dual-way UTM Campaign Builder** — Built-in form builder synchronizes UTM parameters with your destination URLs in real-time (two-way binding).
- 🔒 **Link Validity Ranges & Expiry** — Set activation date ranges (From - To), custom visit limit counters (e.g. active for 3 clicks then expires), single-use restrictions, and custom fallback redirect URLs on expiration instead of static 410 Gone errors.
- ➡️ **Query Parameter Forwarding** — Dynamically forward client query parameters (e.g. ad tokens, discount codes) to the destination URL.
- 🛠️ **Dedicated Settings GUI** — Manage global configuration (routing, Geo-IP, GA4, cache, rate limiting, aggregation) directly inside the Filament panel without modifying files or `.env` files.
- 💻 **Fluent Developer Builder** — Native model query builder pattern and robust programmatic generation APIs.
- 🔑 **Password-Protected Links** — Require a password before redirecting visitors, with session-based unlock.
- ⚠️ **Redirect Warning Pages** — Show an interstitial security page before redirecting to external URLs (phishing/NSFW protection).
- 🎯 **Smart Link Targeting** — Route visitors to different destination URLs based on their device type, country, or via weighted A/B split rotation.
- 🛡️ **Rate Limiting / Bot Protection** — Configurable per-IP rate limits on redirects with automatic `429 Too Many Requests` responses.
- 📊 **Daily Stats Aggregation & Pruning** — Automatic daily summarization of raw visit logs into compact daily stats tables. Configurable retention window prevents unbounded database growth at scale.
- 🎯 **Social Retargeting Pixels** *(new in v1.5)* — Inject Meta Pixel, Google Tag, and LinkedIn Insight tracking scripts client-side via a premium glassmorphic interstitial page. Build remarketing audiences even when redirecting to external domains.
- 🔌 **Developer REST API** *(new in v1.5)* — Full REST API (`GET`, `POST`, `DELETE`) for external integrations. Secured with API Key authentication managed via the Settings panel.
- 📡 **Webhooks** *(new in v1.5)* — Real-time HTTP POST event notifications on every click, link creation, or expiration. Configure per-link or globally, dispatched asynchronously via the queue.
---
@@ -33,7 +72,7 @@ A professional, high-performance **Short URL Manager** plugin for [Filament v5](
Install the package via Composer:
```bash
composer require bjanczak/filament-short-url
composer require janczakb/filament-short-url
```
Publish and run the database migrations:
@@ -47,31 +86,67 @@ php artisan migrate
## Publishing Package Assets
The package is built with standard publishing tags to let developers easily customize and override the default assets within the host application directory:
Customize and override views, translations, or configuration files by publishing the package assets:
### 1. Publish Config File
Copies the default config file to `config/filament-short-url.php` for code-level customization:
Copies the default config file to `config/filament-short-url.php`:
```bash
php artisan vendor:publish --tag=filament-short-url-config
```
### 2. Publish Translation Files
Copies localization files to `lang/vendor/filament-short-url/` so you can modify or add new languages (Polish and English included by default):
Copies localization files to `lang/vendor/filament-short-url/` (English and Polish included by default):
```bash
php artisan vendor:publish --tag=filament-short-url-translations
```
### 3. Publish Blade Views & Templates
Copies the dashboard components, charts, and QR designer templates to `resources/views/vendor/filament-short-url/` to completely override the styling:
Copies the dashboard components, charts, and QR designer templates to `resources/views/vendor/filament-short-url/`:
```bash
php artisan vendor:publish --tag=filament-short-url-views
```
### 4. Publish Everything at Once
### 4. Publish CSS Assets
The plugin ships with a pre-compiled stylesheet. Copy it to your application's public directory so the browser can load it:
```bash
php artisan vendor:publish --provider="Bjanczak\FilamentShortUrl\FilamentShortUrlServiceProvider"
php artisan filament:assets
```
That's all. The plugin's CSS will be served from `public/css/janczakb/filament-short-url/filament-short-url.css` and Filament registers it automatically.
> **You do not need to run Tailwind, Vite, or npm for the plugin styles.** The compiled file is included in the package.
**Tip — automate on every `composer install` / `composer update`:**
Add `filament:assets` to the `post-autoload-dump` scripts in your application's `composer.json` so the assets are always up to date without manual steps:
```json
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi",
"@php artisan filament:assets"
]
}
```
---
> #### 🛠 For Plugin Developers Only
>
> If you are modifying the plugin source and need to recompile its stylesheet after changing Blade/PHP files:
>
> ```bash
> # 1. Recompile the plugin CSS with Tailwind v4
> npx @tailwindcss/cli -i ./packages/filament-short-url/resources/css/plugin.css \
> -o ./packages/filament-short-url/resources/dist/filament-short-url.css --minify
>
> # 2. Re-publish the compiled asset to public/
> php artisan filament:assets
> ```
---
## Setup
@@ -86,28 +161,559 @@ public function panel(Panel $panel): Panel
return $panel
->plugins([
FilamentShortUrlPlugin::make()
->navigationGroup('Tools') // optional
->navigationSort(50), // optional
->navigationGroup('Marketing') // optional — sidebar group name
->navigationLabel('Short Links') // optional — override menu item name
->navigationIcon('heroicon-o-link') // optional — override menu icon
->navigationSort(50), // optional — sort order in sidebar
]);
}
```
### Navigation Configuration Options
All fluent methods on the plugin are optional. If not called, the plugin falls back to defaults or translation files:
| Method | Default | Description |
|--------|---------|-------------|
| `navigationGroup(string)` | `null` | Groups the resource menu item under a sidebar section. |
| `navigationLabel(string)` | `'Short URLs'` | Overrides the menu item display name. |
| `navigationIcon(string)` | `heroicon-o-link` | Overrides the Heroicon used in the sidebar. |
| `navigationSort(int)` | `50` | Controls the sort order within the navigation list. |
---
## Usage in Code
## Global Settings GUI
### 1. Programmatic Creation via Fluent Builder
You can easily create, configure, and append tracking tags to short URLs programmatically using the fluent builder:
The package comes with a built-in admin settings dashboard. You can access it by clicking the **Settings** action button on the top-right header of the Short URLs resource.
Settings are stored dynamically in `storage/app/filament-short-url-settings.json` and immediately override config defaults.
The settings panel allows you to configure:
### 1. General Routing & Queueing
* **Route Prefix**: The slug prepended to short URLs (e.g. `s` for `/s/{key}`).
* **Default Redirect Status**: Choose `302 (Found / Temporary)` or `301 (Moved Permanently)`.
* *Note: `302` is highly recommended for analytics accuracy because browsers cache `301` redirects, skipping subsequent logs.*
* **Key Length**: Default character count (base62) for auto-generated keys (default: `6`).
* **Queue Connection**: Define the Laravel queue connection (e.g. `redis`, `database`, `sync`) used for processing visit analytics asynchronously.
### 2. Geo-IP Country Detection
Toggle country tracking and select from three drivers:
* **Headers** (Edge Resolution): Automatically detects client country using standard edge headers (e.g. Cloudflare's `CF-IPCountry`, AWS CloudFront's `CloudFront-Viewer-Country`, or generic proxies).
* **MaxMind** (Offline Resolution): Reads from a local GeoIP2 database (such as the free GeoLite2-Country database).
* **IP-API** (Online Fallback): Makes an external API call to `ip-api.com` with configurable timeout.
### 3. Google Analytics 4 (GA4) Integration
Sends server-side `short_url_visit` hits using the **GA4 Measurement Protocol API**. This bypasses browser-side AdBlockers entirely.
* **GA4 API Secret**: Create this secret in Google Analytics under `Admin -> Data Streams -> Measurement Protocol API secrets`.
* **Firebase App ID / Measurement ID**: The target analytics stream identifier.
### 4. Counter Buffering (Write-back Caching)
For extremely high-traffic applications, direct database writes for click counts can cause row-locking bottlenecks.
* **Buffer Click Counts**: Toggling this option buffers total and unique visit count increments in the application cache.
* **Cron Synchronization**: When enabled, you must schedule the synchronization command to run periodically (e.g., every minute) to flush counts to the database:
```bash
php artisan short-url:sync-counters
```
In your scheduler (`routes/console.php` or `app/Console/Kernel.php`):
```php
$schedule->command('short-url:sync-counters')->everyMinute();
```
### 5. Performance & Security Tab (new in v1.2.0)
#### High-Traffic Log Management (Aggregation & Pruning)
At scale, the `short_url_visits` table can grow to tens of gigabytes. The aggregation system solves this:
* **Enable Daily Aggregation**: When enabled, the nightly `short-url:aggregate-and-prune` command summarizes the previous day's raw visit records into the compact `short_url_daily_stats` table.
* **Prune Raw Logs After (days)**: Raw visit records older than this threshold are permanently deleted after aggregation. Set to `0` to disable pruning. Default: `90` days.
Schedule the command in your scheduler:
```php
$schedule->command('short-url:aggregate-and-prune')->dailyAt('02:00');
```
#### Rate Limiting / Bot Protection
Prevent redirect abuse and bot traffic flooding:
* **Enable Rate Limiting**: Activates per-IP rate limiting on all redirect routes.
* **Max Redirects Allowed**: Maximum number of redirect requests per IP within the decay window. Default: `60`.
* **Decay Window (seconds)**: The rolling time window for the rate limiter. Default: `60` seconds.
When a client exceeds the limit, a `429 Too Many Requests` response is returned with a `Retry-After` header.
---
## Password-Protected Links (new in v1.2.0)
You can require visitors to enter a password before being redirected. Enable this in the **Targeting & Security** tab of the short URL form:
- Set a plain-text password in the **Access Password** field.
- Visitors will see a styled password prompt page before gaining access.
- The unlock state is stored in the PHP session — visitors only need to enter the password once per session.
```php
// Programmatically — set via fillable attributes
$shortUrl = ShortUrl::destination('https://secret.example.com')
->create();
$shortUrl->update(['password' => 'my-secret-pass']);
```
> **Note**: Passwords are currently stored as plain text. For sensitive use-cases, hash the password and compare with `Hash::check()` by overriding the redirect controller.
---
## Redirect Warning Pages (new in v1.2.0)
Enable the **Show Redirect Warning Page** toggle in the **Targeting & Security** tab to display a safety interstitial before redirecting.
The warning page:
- Shows the destination URL clearly so visitors can verify they trust it.
- Provides **Continue** and **Go Back** buttons.
- Is confirmed via a `?confirmed=1` query parameter — no additional session storage required.
- Is styled to match the password prompt page (glassmorphism, dark mode compatible).
This feature is useful for NSFW links, external partner links, or any URL that leaves a trusted domain.
---
## Smart Link Targeting (new in v1.2.0)
The **Targeting & Security** tab exposes a powerful rule engine that lets you route different visitors to different destinations — all from a single short URL.
### Available Strategies
#### 1. Device-Based Redirects
Route visitors to different URLs based on their device type (detected from User-Agent):
| Device | Detected by User-Agent containing |
|--------|-----------------------------------|
| iOS (Mobile) | `iphone`, `ipad`, `ipod` |
| Android | `android` |
| Desktop | Everything else |
```php
// Programmatic example
$shortUrl->update([
'targeting_rules' => [
'type' => 'device',
'device' => [
'ios' => 'https://apps.apple.com/your-app',
'android' => 'https://play.google.com/your-app',
'desktop' => 'https://example.com/download',
],
],
]);
```
#### 2. Country-Based (Geo-IP) Redirects
Route visitors to country-specific URLs. Requires Geo-IP to be enabled in settings. Falls back to the default `destination_url` for unlisted countries.
```php
$shortUrl->update([
'targeting_rules' => [
'type' => 'geo',
'geo' => [
['country_code' => 'PL', 'url' => 'https://pl.example.com'],
['country_code' => 'US', 'url' => 'https://us.example.com'],
['country_code' => 'DE', 'url' => 'https://de.example.com'],
],
],
]);
```
#### 3. A/B Split Rotation
Distribute traffic across multiple URLs using weighted random selection. Weights are proportional — they do not need to sum to 100.
```php
$shortUrl->update([
'targeting_rules' => [
'type' => 'rotation',
'rotation' => [
['url' => 'https://variant-a.example.com', 'weight' => 70],
['url' => 'https://variant-b.example.com', 'weight' => 30],
],
],
]);
```
> All targeting strategies fall back gracefully to the link's primary `destination_url` if no rule matches.
---
## High-Traffic Optimizations (new in v1.2.0)
### Daily Stats Aggregation
The `short_url_daily_stats` table stores pre-aggregated daily summaries per short URL. Each row contains:
| Column | Description |
|--------|-------------|
| `date` | The calendar day |
| `visits_count` | Total visits |
| `unique_visits_count` | Unique visitors (by hashed IP) |
| `device_stats` | JSON — visit counts by device type |
| `browser_stats` | JSON — visit counts by browser |
| `os_stats` | JSON — visit counts by operating system |
| `country_stats` | JSON — visit counts by country |
| `city_stats` | JSON — visit counts by city |
| `referer_stats` | JSON — visit counts by referer domain |
| `utm_source_stats` | JSON — visit counts by UTM source |
| `utm_medium_stats` | JSON — visit counts by UTM medium |
| `utm_campaign_stats` | JSON — visit counts by UTM campaign |
The `getCachedStats()` model method **automatically merges** data from both tables: historical days come from `short_url_daily_stats`, while today's data comes directly from `short_url_visits` — completely transparent to the dashboard.
### Queue Worker vs. Synchronous Execution
The plugin is designed to be highly reliable and performant regardless of whether your hosting environment runs a background queue worker.
#### 1. With a Queue Worker (Recommended)
If your application runs a queue worker (e.g. via supervisor running `php artisan queue:work`), you should configure the **Queue Connection** in the **Settings** panel (or via `SHORT_URL_QUEUE` env variable) to your primary queue driver (like `redis` or `database`).
- **Performance**: High-speed redirects are prioritized. Visitor clicks, Geo-IP lookups, GA4 hits, and Webhook dispatches are immediately deferred to background queue jobs (`TrackShortUrlVisitJob` and `SendWebhookJob`), keeping redirect response times under 20ms.
- **Worker Configuration**: Ensure your queue listener is running:
```bash
php artisan queue:work --queue=default
```
*(If you customized the queue name in Settings, replace `default` with your custom queue name).*
#### 2. Without a Queue Worker (Sync Driver Fallback)
If you do not run background queue workers, set the **Queue Connection** to `sync`.
- **Automatic Fallback**: The plugin dynamically executes all jobs synchronously on the request thread. The visitor is redirected as soon as the synchronous processes (log recording, webhook calls, etc.) complete.
- **Fault Tolerance (Safety Nets)**: Webhook failures (timeouts, 500 errors) or database tracking glitches can happen. The plugin wraps all synchronous execution points in strict error boundaries (`try/catch`). **A failed tracking job or a slow/offline webhook will NEVER crash the visitor's redirect or programmatic REST API responses.** They are gracefully logged in the background.
### Queue-Based Counter Fallback
When Redis is not available and counter buffering is enabled, the `IncrementVisitJob` is dispatched to the configured queue connection. This guarantees visit counts are not lost during cache evictions or restarts.
---
## Social Retargeting Pixels (new in v1.5.0)
The **Marketing & API** tab in the short URL form lets you attach client-side tracking pixels to any link. When a visitor clicks a link that has pixels configured, instead of an instant 302 redirect the plugin serves a lightweight, premium HTML interstitial page.
### The Interstitial Experience
- **Premium Design**: Built using the exact same modern glassmorphic look as the password protection and warning interstitial pages. Supports dark mode automatically.
- **Brand Customization**: Automatically renders the application logo and the **Site Name Override** (configured globally in Settings, falling back to `config('app.name')`) to ensure the transition page looks professional and trust-instilling.
- **Micro-Animations & Smooth Redirect**: Displays a sleek animated loading spinner and a progress bar that smoothly fills from 0% to 100% in ~220-250ms. This short delay ensures browser execution time for the tracking scripts before performing a seamless `window.location.replace()` to the destination URL.
This unlocks remarketing to people who clicked your links **even when redirecting to external domains** (e.g. booking.com, amazon.com) where you cannot install your own tracking code.
### Supported Pixel Providers
| Field | Provider | Script loaded |
|---|---|---|
| **Meta Pixel ID** | Meta / Facebook Ads | `fbevents.js` via `fbq('init', ...)` |
| **Google Tag / GA4 ID** | Google Ads, GA4 | `gtag.js` via Google Tag Manager |
| **LinkedIn Partner ID** | LinkedIn Insight Tag | `insight.min.js` via LinkedIn |
> **Note:** These pixels fire **client-side** in the visitor's browser — completely separate from the server-side GA4 Measurement Protocol integration. Both systems work in parallel and do not interfere with each other.
### How to use
1. Open any short URL for editing.
2. Navigate to the **Marketing & API** tab.
3. Enter your pixel IDs in the **Retargeting Pixels** section.
4. Save. Done — every click will now trigger the configured tracking scripts.
```php
// Programmatically via model attributes
$shortUrl->update([
'pixel_meta_id' => '1234567890',
'pixel_google_id' => 'G-XXXXXXXXXX',
'pixel_linkedin_id' => '1234567',
]);
```
> **Privacy/GDPR Note:** You are responsible for ensuring that firing these pixels complies with applicable privacy regulations and your cookie consent mechanism.
---
## Developer REST API (new in v1.5.0)
The plugin exposes a REST API that allows external systems (CRMs, Zapier, Make, custom integrations) to manage short URLs programmatically.
### Enabling the API
The API is **disabled by default**. Enable it in **Settings → API & Webhooks → REST API Access → Enable Developer REST API**.
### Authentication
All API endpoints are protected. Include your API key in every request using one of these headers:
```
X-Api-Key: sh_key_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```
or
```
Authorization: Bearer sh_key_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```
**Managing API Keys:** Go to **Settings → API & Webhooks → Developer API Keys** and add named keys. Each key can be individually activated or deactivated without deleting it.
> If the API is disabled globally, all endpoints return `503 Service Unavailable` regardless of the key provided.
### Endpoints
#### `GET /api/short-url/links`
List all short URLs (paginated, 30 per page).
```bash
curl https://yourdomain.com/api/short-url/links \
-H "X-Api-Key: sh_key_your_key_here"
```
**Response:**
```json
{
"data": [
{
"id": 1,
"destination_url": "https://example.com",
"url_key": "abc123",
"short_url": "https://yourdomain.com/s/abc123",
"is_enabled": true,
"redirect_status_code": 302,
"total_visits": 47,
"unique_visits": 31,
"max_visits": null,
"activated_at": null,
"expires_at": null,
"pixel_meta_id": null,
"pixel_google_id": null,
"pixel_linkedin_id": null,
"webhook_url": null,
"notes": null,
"created_at": "2026-06-01T12:00:00+00:00"
}
],
"meta": {
"current_page": 1,
"last_page": 3,
"per_page": 30,
"total": 72
}
}
```
#### `POST /api/short-url/links`
Create a new short URL.
```bash
curl -X POST https://yourdomain.com/api/short-url/links \
-H "X-Api-Key: sh_key_your_key_here" \
-H "Content-Type: application/json" \
-d '{
"destination_url": "https://example.com/product",
"url_key": "promo26",
"notes": "Summer campaign",
"single_use": false,
"max_visits": 1000,
"pixel_meta_id": "1234567890",
"webhook_url": "https://api.mycrm.com/clicks"
}'
```
**Accepted fields:**
| Field | Type | Required | Description |
|---|---|---|---|
| `destination_url` | string (URL) | ✅ | Target URL |
| `url_key` | string | ❌ | Custom slug (auto-generated if omitted) |
| `notes` | string | ❌ | Internal notes |
| `is_enabled` | boolean | ❌ | Active status (default: `true`) |
| `redirect_status_code` | integer (301/302) | ❌ | HTTP redirect code |
| `single_use` | boolean | ❌ | Expire after first click |
| `forward_query_params` | boolean | ❌ | Forward query string to destination |
| `max_visits` | integer | ❌ | Click limit before expiry |
| `expiration_redirect_url` | string (URL) | ❌ | Fallback URL on expiry |
| `activated_at` | datetime | ❌ | Activation timestamp |
| `expires_at` | datetime | ❌ | Expiration timestamp |
| `pixel_meta_id` | string | ❌ | Meta Pixel ID |
| `pixel_google_id` | string | ❌ | Google Tag / GA4 ID |
| `pixel_linkedin_id` | string | ❌ | LinkedIn Partner ID |
| `webhook_url` | string (URL) | ❌ | Per-link webhook endpoint |
**Response:** `201 Created` with the created link object.
#### `DELETE /api/short-url/links/{id}`
Permanently delete a short URL by its ID.
```bash
curl -X DELETE https://yourdomain.com/api/short-url/links/42 \
-H "X-Api-Key: sh_key_your_key_here"
```
**Response:** `200 OK`
```json
{ "message": "Short URL deleted successfully." }
```
### Error Responses
| HTTP Code | Reason |
|---|---|
| `401 Unauthorized` | Missing or invalid API key |
| `422 Unprocessable Entity` | Validation error (see `errors` field in response) |
| `503 Service Unavailable` | REST API is disabled in Settings |
---
## Webhooks (new in v1.5.0)
Webhooks allow external systems to receive real-time HTTP POST notifications when events occur on your short URLs. Payloads are dispatched **asynchronously** via the Laravel Queue — redirects are never blocked.
### Configuration
Webhooks can be configured at two levels:
**1. Per-link Webhook (Dedicated Webhook URL)**:
* **Where to configure**: Set the `Dedicated Webhook URL` in the **Marketing & API** tab of a specific short URL (or pass it via the `webhook_url` parameter in the REST API).
* **How it works**: When a visitor clicks the short URL, or when the link is programmatically created via the REST API, a webhook notification is sent directly to this URL.
* **Bypassing Global Filters**: Dedicated webhooks **always fire** for these events and are completely independent of the global *Monitored Webhook Events* settings. This is useful for third-party landing pages or integrations that need to track a specific link's traffic without routing all package events.
**2. Global Webhook**:
* **Where to configure**: Set a **Global Webhook URL** in **Settings → API & Webhooks → Global Webhook Configuration**.
* **How it works**: Fires for all links that *do not* have their own Dedicated Webhook URL configured. It will only fire for the specific event types selected in the **Monitored Webhook Events** setting.
### Monitored Events
| Event key | When fired |
|---|---|
| `visited` | A visitor clicks the short URL |
| `created` | A new short URL is created via the REST API |
| `expired` | A link reaches its expiration date |
| `limit_reached` | A link reaches its `max_visits` click limit |
Select which events to monitor in **Settings → API & Webhooks → Monitored Webhook Events**.
### Payload Format
All webhook requests are HTTP POST with `Content-Type: application/json` and the following payload structure:
```json
{
"event": "visited",
"timestamp": "2026-06-02T10:00:00+00:00",
"short_url": {
"id": 1,
"destination_url": "https://example.com",
"url_key": "abc123",
"short_url": "https://yourdomain.com/s/abc123",
"total_visits": 48,
"unique_visits": 32
},
"visit": {
"id": 101,
"visited_at": "2026-06-02T10:00:00+00:00",
"device_type": "desktop",
"browser": "Chrome",
"browser_version": "124.0",
"operating_system": "Windows",
"operating_system_version": "10",
"country": "Poland",
"country_code": "PL",
"city": "Warsaw",
"referer_url": "https://linkedin.com",
"referer_host": "linkedin.com",
"utm_source": "linkedin",
"utm_medium": "social",
"utm_campaign": "spring_sale",
"utm_term": null,
"utm_content": null
}
}
```
### Retry Policy
If the webhook endpoint returns a non-2xx response or is unreachable, the `SendWebhookJob` will automatically retry up to **3 times** with a **10-second backoff** between attempts. Failed jobs land in your queue's failed jobs table after exhausting retries.
### Webhook Priority (per-link vs global)
The resolution order is:
1. If the short URL has its own `webhook_url` → use it (always fires, regardless of global event selection).
2. If no per-link URL is set, and a **Global Webhook URL** is configured, and the event type is in the selected **Monitored Events** list → use the global URL.
3. Otherwise no webhook is fired.
---
## Configuration Reference (.env)
You can also pre-configure all parameters via your `.env` file:
| Environment Variable | Config Path | Default | Description |
|---|---|---|---|
| `SHORT_URL_PREFIX` | `route_prefix` | `'s'` | URL prefix for short URL redirects. |
| `SHORT_URL_GEO_IP` | `geo_ip.enabled` | `true` | Globally enable/disable Geo-IP tracking. |
| `SHORT_URL_GEO_IP_DRIVER` | `geo_ip.driver` | `'headers'` | Geo-IP resolver driver (`headers`, `maxmind`, `ip-api`). |
| `SHORT_URL_MAXMIND_DB` | `geo_ip.maxmind.database_path` | `storage_path('geoip/GeoLite2-Country.mmdb')` | Path to local MaxMind db. |
| `SHORT_URL_STATS_CACHE_TTL` | `geo_ip.stats_cache_ttl` | `300` | Caching TTL in seconds for dashboard charts. |
| `SHORT_URL_QUEUE` | `queue_connection` | `'sync'` | Queue connection for recording visits. |
| `SHORT_URL_CACHE_TTL` | `cache_ttl` | `3600` | Redirection model caching TTL (set to `0` to disable). |
| `GA4_API_SECRET` | `ga4.api_secret` | `null` | Google Analytics 4 Measurement Protocol API Secret. |
| `FIREBASE_APP_ID` | `ga4.firebase_app_id` | `null` | Google Analytics 4 Firebase App ID (or uses Measurement ID). |
| `SHORT_URL_COUNTER_BUFFERING` | `counter_buffering.enabled` | `false` | Buffer click counts in cache (flushed via console command). |
| `SHORT_URL_TRUST_CDN_HEADERS` | `trust_cdn_headers` | `false` | Trust proxy/CDN headers to extract real client IP and country. |
| `SHORT_URL_PRUNING_ENABLED` | `pruning.enabled` | `true` | Enable daily aggregation and log pruning. |
| `SHORT_URL_PRUNING_DAYS` | `pruning.retention_days` | `90` | Number of days to retain raw visit logs. |
| `SHORT_URL_RATE_LIMITING` | `rate_limiting.enabled` | `false` | Enable per-IP redirect rate limiting. |
| `SHORT_URL_RATE_LIMIT_MAX` | `rate_limiting.max_attempts` | `60` | Max redirect requests within the decay window. |
| `SHORT_URL_RATE_LIMIT_DECAY` | `rate_limiting.decay_seconds` | `60` | Rate limiter rolling window in seconds. |
---
## Artisan Commands
| Command | Description |
|---------|-------------|
| `short-url:sync-counters` | Flushes buffered visit counts from cache to the database. Schedule every minute when counter buffering is enabled. |
| `short-url:aggregate-and-prune` | Aggregates previous days' raw visits into `short_url_daily_stats` and prunes raw records older than the configured retention period. Schedule daily (e.g. at `02:00`). |
### Automatic Scheduler Registration (v1.3.0)
As of version `1.3.0`, **you no longer need to manually copy scheduled commands into your host application code!** The plugin automatically registers the required tasks inside its ServiceProvider booted phase, dynamically respecting your Settings GUI toggles:
- **`short-url:aggregate-and-prune`** is scheduled **daily at 02:00** (runs automatically only if **Enable Daily Aggregation** is ON).
- **`short-url:sync-counters`** is scheduled **every minute** (runs automatically only if **Buffer Visit Counts in Cache** is ON).
> [!IMPORTANT]
> **Cron Setup Required**:
> For the scheduler to fire these tasks automatically, your server must run the standard Laravel Scheduler cron job. Add this single cron entry to your server:
> ```bash
> * * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
> ```
> *Note: These commands execute synchronously within the scheduling process. You do **not** need a queue worker (`php artisan queue:work`) to run them.*
If you prefer to configure the schedule manually, you can still define them in `routes/console.php` (ensure the corresponding toggles are turned OFF in your Settings panel to avoid redundant executions):
```php
// routes/console.php
use Illuminate\Support\Facades\Schedule;
// Flush buffered click counts every minute (only if counter buffering is enabled)
Schedule::command('short-url:sync-counters')->everyMinute();
// Aggregate stats and prune old raw visits nightly
Schedule::command('short-url:aggregate-and-prune')->dailyAt('02:00');
```
---
## Programmatic Usage (Fluent Builder)
You can programmatically generate, customize, and trace short URLs anywhere in your code using the static `destination` builder on the `ShortUrl` model:
```php
use Bjanczak\FilamentShortUrl\Models\ShortUrl;
$shortUrl = ShortUrl::destination('https://example.com/very/long/url')
->urlKey('promo2026') // optional, auto-generated if empty
->notes('Spring campaign promo')
->singleUse() // deactivates after first visit
->forwardQueryParams() // forward incoming visitor query strings
->withTracing([ // dynamically filters and appends UTM parameters
$shortUrl = ShortUrl::destination('https://example.com/products/promo')
->urlKey('promo2026') // Optional, auto-generated base62 key if omitted
->notes('Spring social promo')
->singleUse() // Deactivates the link automatically after the first visit
->forwardQueryParams() // Appends incoming URL query strings to destination
->expiresAt(now()->addDays(7)) // Automatic link expiration
->trackVisits(true) // Enable or disable click logs
->withTracing([ // Dynamically filter and append UTM parameters
'utm_source' => 'linkedin',
'utm_medium' => 'social',
'utm_campaign' => 'spring_sale',
@@ -115,11 +721,41 @@ $shortUrl = ShortUrl::destination('https://example.com/very/long/url')
])
->create();
// Output the public short URL string
echo $shortUrl->getShortUrl(); // https://yourapp.com/s/promo2026
// Get the full URL string
echo $shortUrl->getShortUrl(); // https://yourdomain.com/s/promo2026
```
### 2. Standard Service Injection
### Fluent Builder API Reference
| Method | Argument Type | Description |
|--------|---------------|-------------|
| `urlKey()` | `string` | Sets a custom redirection key (slug). |
| `notes()` | `string` | Appends internal notes for administrators. |
| `singleUse()` | `bool` (default `true`) | Makes the short URL expire immediately after the first successful click. |
| `forwardQueryParams()` | `bool` (default `true`) | Forwards client-side incoming parameters (e.g. `?gclid=xxx`) to the final target. |
| `expiresAt()` | `DateTimeInterface\|Carbon\|null` | Automatically sets an expiration timestamp after which the URL is inactive. |
| `activatedAt()` | `DateTimeInterface\|Carbon\|null` | Sets the timestamp from which the URL is active. |
| `deactivatedAt()` | `DateTimeInterface\|Carbon\|null` | Sets the timestamp after which the URL is inactive. |
| `maxVisits()` | `int\|null` | Sets a custom limit of total visits allowed. |
| `expirationRedirectUrl()` | `string\|null` | Sets a custom URL to redirect to when expired/inactive. |
| `trackVisits()` | `bool` (default `true`) | Toggles statistical logging for this link. |
| `withTracing()` | `array` | Appends non-empty tracking parameters (like UTM codes) directly to the target URL. |
| `create()` | `ShortUrl` | Persists the model to the database and returns the `ShortUrl` instance. |
---
## Model Helpers & Service
### ShortUrl Model Methods
* `isActive(): bool` — Checks if the short URL is enabled and within its activation/expiration timestamps.
* `isExpired(): bool` — Checks if the URL has passed its expiration date.
* `getShortUrl(): string` — Resolves the complete URL string.
* `incrementVisits(bool $isUnique = false): void` — Atomically increments visit counts (with Redis buffering or queue fallback).
* `getCachedStats(): array` — Returns cached key metrics for dashboard charts. Automatically merges daily aggregated stats with today's raw visits.
* `resolveDestinationUrl(Request $request): string` — Evaluates active targeting rules (device, geo, rotation) and returns the correct destination URL for the current visitor.
### Injecting the Service
For standard creations, you can inject `ShortUrlService`:
```php
use Bjanczak\FilamentShortUrl\Services\ShortUrlService;
@@ -135,7 +771,7 @@ $shortUrl = $service->create([
## Events
You can listen to short URL visits dynamically in your application (e.g. for real-time alerts or external webhooks):
The package fires the `ShortUrlVisited` event inside the queue job. You can listen to it to trigger custom logic, Slack notifications, or syncing external CRMs:
```php
use Bjanczak\FilamentShortUrl\Events\ShortUrlVisited;
@@ -143,12 +779,72 @@ use Illuminate\Support\Facades\Event;
Event::listen(ShortUrlVisited::class, function (ShortUrlVisited $event) {
$event->shortUrl; // The ShortUrl model instance
$event->visit; // The ShortUrlVisit model instance (contains resolved client IP, browser, OS, country, etc.)
$event->visit; // The ShortUrlVisit model (contains resolved IP, country, device, browser, OS, referrer)
});
```
---
## Visitor Filtering (Bot Detection)
Visits from scrapers, search bots, and web crawlers are automatically ignored to keep stats clean. The system matches user agents against a custom list (including Googlebot, Bingbot, Applebot, Facebook, Twitter, and generic curl/http request clients).
---
## Database Compatibility
All migrations are compatible with **SQLite**, **MySQL**, and **PostgreSQL**:
- No MySQL-specific `ENUM` types — `device_type` uses `VARCHAR(20)` validated at PHP level.
- No `->after()` column ordering hints — fully cross-database.
- JSON columns work natively on MySQL 5.7.8+ and are stored as TEXT on SQLite.
---
## Changelog
### v1.6.0
- **Google Safe Browsing Integration** — Automatic safety checks against Google's API during link creation or modification. Includes bypass settings, asynchronous checking option, and alert badges.
- **VPN / Proxy / Bot Filtering** — Detect and filter out VPN/proxy traffic and Tor nodes using external proxy detection APIs to keep traffic analytics clean.
- **Visitor World Map Widget** — Live interactive SVG world map showing clicks distribution per country, custom intensity highlighting, and hover details.
- **Enhanced Caching & Chart Formatting** — Improved analytics caching for high volumes, and clean `d.m` date formatting (removed year) on visitor stats charts.
### v1.5.1
- **REST API On/Off Toggle** — Enable or disable the entire developer REST API from Settings → API & Webhooks without touching code. Returns `503 Service Unavailable` when disabled. Toggle takes effect immediately without route cache clearing.
### v1.5.0
- **Social Retargeting Pixels** — Attach Meta Pixel, Google Tag (GA4/Ads), and LinkedIn Insight Tag to any short URL. A premium glassmorphic interstitial page executes pixel scripts in the visitor's browser before forwarding them to the destination. Enables building remarketing audiences even on external domains.
- **Developer REST API** — Full `GET /api/short-url/links`, `POST /api/short-url/links`, and `DELETE /api/short-url/links/{id}` endpoints with API Key authentication (managed via Settings UI). Supports creating links with all available attributes including pixels and webhooks.
- **Webhook System** — Real-time HTTP POST notifications on `visited`, `created`, `expired`, and `limit_reached` events. Configurable per-link or globally. Dispatched asynchronously via `SendWebhookJob` with 3-attempt retry policy and 10-second backoff.
- **Settings: API & Webhooks Tab** — New settings tab to manage global webhook URL, monitored event types, and developer API key management with name labels and per-key activation toggles.
### v1.4.0
- **Validity Date Ranges (From-To)** — Set activation dates (`activated_at` and `expires_at`) to control exactly when a short link is active.
- **Custom Visit Limit Counters** — Define a custom maximum visit limit (`max_visits`) after which a link automatically expires (e.g., active for 3 hits).
- **Custom Expiration Fallbacks** — Redirect expired/inactive visitors to a custom `expiration_redirect_url` rather than showing a static 410 Gone error page.
- **Reactive Validity Controls** — Master switch to toggle date limits, including bidirectional datetime picker constraints (Active From cannot exceed Expires At and vice versa) and custom UI field visibility.
- **Smart Model Observers** — Automatic cleanup of unused parameters (like clearing `max_visits` if `single_use` is enabled, and clearing expiration fallbacks if date limits are off) to guarantee database consistency.
- **Fluent Builder APIs** — Fluent method additions (`activatedAt()`, `deactivatedAt()`, `maxVisits()`, `expirationRedirectUrl()`) in the developer query builder.
### v1.3.0
- **Automatic Scheduler Registration** — Zero-configuration task registration within the ServiceProvider booted phase (dynamically honors Settings toggles).
- **Interactive Settings Validators** — Adds real-time "Test connection" verify action for GA4 Measurement Protocol and "Verify file" action for MaxMind database paths.
- **Robust Table Row Copy Action** — High-reliability, conflict-free click-to-copy in table rows with built-in fallback helper for non-HTTPS (secure context) browser environments.
- **Filament v5 Notification API** — Seamless integration of the new `FilamentNotification` class API inside client-side JS.
- **Asset Compilation Guide** — Explains Tailwind CLI CSS compilation and Filament asset publishing workflows for package extensions.
### v1.2.0
- **Password-protected links** — Session-based unlock flow with a styled prompt page.
- **Redirect warning pages** — Interstitial security screen before external redirects.
- **Smart targeting** — Device-based, Country/Geo-based, and A/B weighted rotation rules per link.
- **Rate limiting** — Configurable per-IP redirect throttling with 429 responses.
- **Daily stats aggregation** — Nightly `short-url:aggregate-and-prune` command for scalable log management.
- **Counter buffering fallback** — `IncrementVisitJob` as queue-based fallback when Redis is unavailable.
- **Database compatibility** — Replaced `ENUM` with `VARCHAR`, removed MySQL-only `->after()` calls.
- **Extended Settings GUI** — New "Performance & Security" tab for aggregation and rate limiting configuration.
- **Polish translations** — Full `pl` locale support for all new features.
---
## License
MIT

BIN
art/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

BIN
art/2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 KiB

BIN
art/3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 362 KiB

BIN
art/4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 406 KiB

View File

@@ -14,6 +14,16 @@ return [
*/
'route_prefix' => env('SHORT_URL_PREFIX', 's'),
/*
|--------------------------------------------------------------------------
| Site Name Override
|--------------------------------------------------------------------------
| The brand or site name displayed on the password prompt, redirect warnings,
| and pixel loading screens. Falls back to config('app.name') if empty.
|
*/
'site_name' => env('SHORT_URL_SITE_NAME'),
/*
|--------------------------------------------------------------------------
| Default Redirect Status Code
@@ -46,7 +56,7 @@ return [
'driver' => env('SHORT_URL_GEO_IP_DRIVER', 'headers'), // 'headers', 'maxmind', 'ip-api'
'timeout' => 3, // seconds to wait for geo-ip response
'maxmind' => [
'database_path' => env('SHORT_URL_MAXMIND_DB', database_path('geoip/GeoLite2-Country.mmdb')),
'database_path' => env('SHORT_URL_MAXMIND_DB', storage_path('geoip/GeoLite2-Country.mmdb')),
],
'stats_cache_ttl' => env('SHORT_URL_STATS_CACHE_TTL', 300), // 5 minutes caching for stats page calculations
],
@@ -93,6 +103,15 @@ return [
*/
'queue_connection' => env('SHORT_URL_QUEUE', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Name
|--------------------------------------------------------------------------
| The queue name to which visit tracking and counter jobs are dispatched.
|
*/
'queue_name' => env('SHORT_URL_QUEUE_NAME', 'default'),
/*
|--------------------------------------------------------------------------
| Redirect Cache TTL
@@ -127,9 +146,74 @@ return [
'foreground_color' => '#000000',
'background_color' => '#ffffff',
'gradient_enabled' => false,
'gradient_from' => '#000000',
'gradient_to' => '#ffffff',
'gradient_from' => '#4f46e5',
'gradient_to' => '#06b6d4',
'gradient_type' => 'linear',
],
/*
|--------------------------------------------------------------------------
| Counter Buffering (Write-back Caching)
|--------------------------------------------------------------------------
| For high-traffic applications, direct database writes on every visit
| can cause locks. Enable this to buffer total/unique visit counts in
| cache, then sync them to the database periodically via a scheduled task.
*/
'counter_buffering' => [
'enabled' => (bool) env('SHORT_URL_COUNTER_BUFFERING', false),
'cache_key_prefix' => 'filament-short-url:buffer:',
],
/*
|--------------------------------------------------------------------------
| Trust CDN/Proxy Headers
|--------------------------------------------------------------------------
| If your application sits behind a CDN (like Cloudflare, AWS CloudFront)
| or a reverse proxy, set this to true to parse real visitor IP addresses
| and country codes from proxy headers. Only enable this if you are
| actually behind a proxy to prevent client IP spoofing!
|
*/
'trust_cdn_headers' => (bool) env('SHORT_URL_TRUST_CDN_HEADERS', false),
/*
|--------------------------------------------------------------------------
| Data Pruning & Aggregation
|--------------------------------------------------------------------------
| To keep the database clean and fast, raw visit logs can be aggregated
| into daily statistics and pruned after a retention period.
|
*/
'pruning' => [
'enabled' => env('SHORT_URL_PRUNING_ENABLED', true),
'retention_days' => env('SHORT_URL_PRUNING_DAYS', 90),
],
/*
|--------------------------------------------------------------------------
| Rate Limiting
|--------------------------------------------------------------------------
| Protect redirect routes from bot abuse and brute force by enabling
| rate limiting.
|
*/
'rate_limiting' => [
'enabled' => env('SHORT_URL_RATE_LIMITING', false),
'max_attempts' => env('SHORT_URL_RATE_LIMIT_MAX', 60),
'decay_seconds' => env('SHORT_URL_RATE_LIMIT_DECAY', 60),
],
/*
|--------------------------------------------------------------------------
| Redirect Route Middleware
|--------------------------------------------------------------------------
| The middleware list applied to the short URL redirect route.
| By default, standard web middleware and rate limiting are applied.
|
*/
'middleware' => [
'web',
'throttle:120,1',
],
];

View File

@@ -27,8 +27,8 @@ return new class extends Migration
$table->string('operating_system', 100)->nullable();
$table->string('operating_system_version', 50)->nullable();
// Device classification
$table->enum('device_type', ['desktop', 'mobile', 'tablet', 'robot'])->nullable()->index();
// Device classification ('desktop', 'mobile', 'tablet', 'robot') — validated at PHP level
$table->string('device_type', 20)->nullable()->index();
// Traffic source
$table->text('referer_url')->nullable();

View File

@@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('short_url_visits', function (Blueprint $table): void {
$table->string('city', 100)->nullable();
$table->string('referer_host', 255)->nullable()->index();
$table->string('utm_source', 100)->nullable()->index();
$table->string('utm_medium', 100)->nullable()->index();
$table->string('utm_campaign', 100)->nullable()->index();
$table->string('utm_term', 100)->nullable();
$table->string('utm_content', 100)->nullable();
});
}
public function down(): void
{
Schema::table('short_url_visits', function (Blueprint $table): void {
$table->dropColumn([
'city',
'referer_host',
'utm_source',
'utm_medium',
'utm_campaign',
'utm_term',
'utm_content',
]);
});
}
};

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('short_urls', function (Blueprint $table): void {
$table->string('password', 255)->nullable();
$table->boolean('show_warning_page')->default(false);
$table->json('targeting_rules')->nullable();
});
}
public function down(): void
{
Schema::table('short_urls', function (Blueprint $table): void {
$table->dropColumn([
'password',
'show_warning_page',
'targeting_rules',
]);
});
}
};

View File

@@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('short_url_daily_stats', function (Blueprint $table): void {
$table->id();
$table->foreignId('short_url_id')
->constrained('short_urls')
->cascadeOnDelete();
$table->date('date');
$table->integer('visits_count')->default(0);
$table->integer('unique_visits_count')->default(0);
$table->json('device_stats')->nullable();
$table->json('browser_stats')->nullable();
$table->json('os_stats')->nullable();
$table->json('country_stats')->nullable();
$table->json('city_stats')->nullable();
$table->json('referer_stats')->nullable();
$table->json('utm_source_stats')->nullable();
$table->json('utm_medium_stats')->nullable();
$table->json('utm_campaign_stats')->nullable();
$table->timestamps();
$table->unique(['short_url_id', 'date']);
});
}
public function down(): void
{
Schema::dropIfExists('short_url_daily_stats');
}
};

View File

@@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('short_urls', function (Blueprint $table): void {
$table->unsignedInteger('max_visits')->nullable();
$table->string('expiration_redirect_url', 2048)->nullable();
});
}
public function down(): void
{
Schema::table('short_urls', function (Blueprint $table): void {
$table->dropColumn(['max_visits', 'expiration_redirect_url']);
});
}
};

View File

@@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('short_urls', function (Blueprint $table) {
$table->string('pixel_meta_id', 100)->nullable();
$table->string('pixel_google_id', 100)->nullable();
$table->string('pixel_linkedin_id', 100)->nullable();
$table->string('webhook_url', 2048)->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('short_urls', function (Blueprint $table) {
$table->dropColumn([
'pixel_meta_id',
'pixel_google_id',
'pixel_linkedin_id',
'webhook_url',
]);
});
}
};

View File

@@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('short_url_visits', function (Blueprint $table): void {
$table->boolean('is_bot')->default(false)->index();
$table->boolean('is_proxy')->default(false)->index();
});
}
public function down(): void
{
Schema::table('short_url_visits', function (Blueprint $table): void {
$table->dropColumn(['is_bot', 'is_proxy']);
});
}
};

17
resources/css/plugin.css Normal file
View File

@@ -0,0 +1,17 @@
@import "tailwindcss";
@source "../../src/**/*.php";
@source "../../resources/views/**/*.blade.php";
.short-url-card {
position: relative !important;
}
.short-url-card .fi-ta-actions {
position: absolute !important;
top: 1.25rem !important;
right: 1.25rem !important;
z-index: 10 !important;
margin: 0 !important;
padding: 0 !important;
}

2
resources/dist/filament-short-url.css vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,253 @@
<?php
return [
'AF' => 'Afghanistan',
'AX' => 'Åland Islands',
'AL' => 'Albania',
'DZ' => 'Algeria',
'AS' => 'American Samoa',
'AD' => 'Andorra',
'AO' => 'Angola',
'AI' => 'Anguilla',
'AQ' => 'Antarctica',
'AG' => 'Antigua and Barbuda',
'AR' => 'Argentina',
'AM' => 'Armenia',
'AW' => 'Aruba',
'AU' => 'Australia',
'AT' => 'Austria',
'AZ' => 'Azerbaijan',
'BS' => 'Bahamas',
'BH' => 'Bahrain',
'BD' => 'Bangladesh',
'BB' => 'Barbados',
'BY' => 'Belarus',
'BE' => 'Belgium',
'BZ' => 'Belize',
'BJ' => 'Benin',
'BM' => 'Bermuda',
'BT' => 'Bhutan',
'BO' => 'Bolivia',
'BQ' => 'Bonaire, Sint Eustatius and Saba',
'BA' => 'Bosnia and Herzegovina',
'BW' => 'Botswana',
'BV' => 'Bouvet Island',
'BR' => 'Brazil',
'IO' => 'British Indian Ocean Territory',
'BN' => 'Brunei Darussalam',
'BG' => 'Bulgaria',
'BF' => 'Burkina Faso',
'BI' => 'Burundi',
'CV' => 'Cabo Verde',
'KH' => 'Cambodia',
'CM' => 'Cameroon',
'CA' => 'Canada',
'KY' => 'Cayman Islands',
'CF' => 'Central African Republic',
'TD' => 'Chad',
'CL' => 'Chile',
'CN' => 'China',
'CX' => 'Christmas Island',
'CC' => 'Cocos (Keeling) Islands',
'CO' => 'Colombia',
'KM' => 'Comoros',
'CD' => 'Congo (Democratic Republic)',
'CG' => 'Congo (Republic)',
'CK' => 'Cook Islands',
'CR' => 'Costa Rica',
'CI' => 'Côte d\'Ivoire',
'HR' => 'Croatia',
'CU' => 'Cuba',
'CW' => 'Curaçao',
'CY' => 'Cyprus',
'CZ' => 'Czech Republic',
'DK' => 'Denmark',
'DJ' => 'Djibouti',
'DM' => 'Dominica',
'DO' => 'Dominican Republic',
'EC' => 'Ecuador',
'EG' => 'Egypt',
'SV' => 'El Salvador',
'GQ' => 'Equatorial Guinea',
'ER' => 'Eritrea',
'EE' => 'Estonia',
'SZ' => 'Eswatini',
'ET' => 'Ethiopia',
'FK' => 'Falkland Islands',
'FO' => 'Faroe Islands',
'FJ' => 'Fiji',
'FI' => 'Finland',
'FR' => 'France',
'GF' => 'French Guiana',
'PF' => 'French Polynesia',
'TF' => 'French Southern Territories',
'GA' => 'Gabon',
'GM' => 'Gambia',
'GE' => 'Georgia',
'DE' => 'Germany',
'GH' => 'Ghana',
'GI' => 'Gibraltar',
'GR' => 'Greece',
'GL' => 'Greenland',
'GD' => 'Grenada',
'GP' => 'Guadeloupe',
'GU' => 'Guam',
'GT' => 'Guatemala',
'GG' => 'Guernsey',
'GN' => 'Guinea',
'GW' => 'Guinea-Bissau',
'GY' => 'Guyana',
'HT' => 'Haiti',
'HM' => 'Heard Island and McDonald Islands',
'VA' => 'Holy See',
'HN' => 'Honduras',
'HK' => 'Hong Kong',
'HU' => 'Hungary',
'IS' => 'Iceland',
'IN' => 'India',
'ID' => 'Indonesia',
'IR' => 'Iran',
'IQ' => 'Iraq',
'IE' => 'Ireland',
'IM' => 'Isle of Man',
'IL' => 'Israel',
'IT' => 'Italy',
'JM' => 'Jamaica',
'JP' => 'Japan',
'JE' => 'Jersey',
'JO' => 'Jordan',
'KZ' => 'Kazakhstan',
'KE' => 'Kenya',
'KI' => 'Kiribati',
'KP' => 'North Korea',
'KR' => 'South Korea',
'KW' => 'Kuwait',
'KG' => 'Kyrgyzstan',
'LA' => 'Lao People\'s Democratic Republic',
'LV' => 'Latvia',
'LB' => 'Lebanon',
'LS' => 'Lesotho',
'LR' => 'Liberia',
'LY' => 'Libya',
'LI' => 'Liechtenstein',
'LT' => 'Lithuania',
'LU' => 'Luxembourg',
'MO' => 'Macao',
'MG' => 'Madagascar',
'MW' => 'Malawi',
'MY' => 'Malaysia',
'MV' => 'Maldives',
'ML' => 'Mali',
'MT' => 'Malta',
'MH' => 'Marshall Islands',
'MQ' => 'Martinique',
'MR' => 'Mauritania',
'MU' => 'Mauritius',
'YT' => 'Mayotte',
'MX' => 'Mexico',
'FM' => 'Micronesia',
'MD' => 'Moldova',
'MC' => 'Monaco',
'MN' => 'Mongolia',
'ME' => 'Montenegro',
'MS' => 'Montserrat',
'MA' => 'Morocco',
'MZ' => 'Mozambique',
'MM' => 'Myanmar',
'NA' => 'Namibia',
'NR' => 'Nauru',
'NP' => 'Nepal',
'NL' => 'Netherlands',
'NC' => 'New Caledonia',
'NZ' => 'New Zealand',
'NI' => 'Nicaragua',
'NE' => 'Niger',
'NG' => 'Nigeria',
'NU' => 'Niue',
'NF' => 'Norfolk Island',
'MK' => 'North Macedonia',
'MP' => 'Northern Mariana Islands',
'NO' => 'Norway',
'OM' => 'Oman',
'PK' => 'Pakistan',
'PW' => 'Palau',
'PS' => 'Palestine',
'PA' => 'Panama',
'PG' => 'Papua New Guinea',
'PY' => 'Paraguay',
'PE' => 'Peru',
'PH' => 'Philippines',
'PN' => 'Pitcairn',
'PL' => 'Poland',
'PT' => 'Portugal',
'PR' => 'Puerto Rico',
'QA' => 'Qatar',
'RE' => 'Réunion',
'RO' => 'Romania',
'RU' => 'Russian Federation',
'RW' => 'Rwanda',
'BL' => 'Saint Barthélemy',
'SH' => 'Saint Helena, Ascension and Tristan da Cunha',
'KN' => 'Saint Kitts and Nevis',
'LC' => 'Saint Lucia',
'MF' => 'Saint Martin (French part)',
'PM' => 'Saint Pierre and Miquelon',
'VC' => 'Saint Vincent and the Grenadines',
'WS' => 'Samoa',
'SM' => 'San Marino',
'ST' => 'Sao Tome and Principe',
'SA' => 'Saudi Arabia',
'SN' => 'Senegal',
'RS' => 'Serbia',
'SC' => 'Seychelles',
'SL' => 'Sierra Leone',
'SG' => 'Singapore',
'SX' => 'Sint Maarten (Dutch part)',
'SK' => 'Slovakia',
'SI' => 'Slovenia',
'SB' => 'Solomon Islands',
'SO' => 'Somalia',
'ZA' => 'South Africa',
'GS' => 'South Georgia and the South Sandwich Islands',
'SS' => 'South Sudan',
'ES' => 'Spain',
'LK' => 'Sri Lanka',
'SD' => 'Sudan',
'SR' => 'Suriname',
'SJ' => 'Svalbard and Jan Mayen',
'SE' => 'Sweden',
'CH' => 'Switzerland',
'SY' => 'Syrian Arab Republic',
'TW' => 'Taiwan',
'TJ' => 'Tajikistan',
'TZ' => 'Tanzania',
'TH' => 'Thailand',
'TL' => 'Timor-Leste',
'TG' => 'Togo',
'TK' => 'Tokelau',
'TO' => 'Tonga',
'TT' => 'Trinidad and Tobago',
'TN' => 'Tunisia',
'TR' => 'Turkey',
'TM' => 'Turkmenistan',
'TC' => 'Turks and Caicos Islands',
'TV' => 'Tuvalu',
'UG' => 'Uganda',
'UA' => 'Ukraine',
'AE' => 'United Arab Emirates',
'GB' => 'United Kingdom',
'UM' => 'United States Minor Outlying Islands',
'US' => 'United States',
'UY' => 'Uruguay',
'UZ' => 'Uzbekistan',
'VU' => 'Vanuatu',
'VE' => 'Venezuela',
'VN' => 'Viet Nam',
'VG' => 'Virgin Islands (British)',
'VI' => 'Virgin Islands (U.S.)',
'WF' => 'Wallis and Futuna',
'EH' => 'Western Sahara',
'YE' => 'Yemen',
'ZM' => 'Zambia',
'ZW' => 'Zimbabwe',
];

View File

@@ -1,7 +1,7 @@
<?php
return [
'navigation_label' => 'Short URLs',
'navigation_label' => 'Short Links',
'navigation_group' => 'Tools',
'resource_title' => 'Short URL',
@@ -24,6 +24,13 @@ return [
'forward_query_params' => 'Forward Query Parameters',
'forward_query_params_helper' => 'Append incoming query parameters (like UTM tags) to the destination URL.',
'expires_at' => 'Expires At',
'activated_at' => 'Active From',
'max_visits' => 'Max Visits Limit',
'max_visits_helper' => 'Optional limit of total visits allowed before this link is deactivated.',
'expiration_redirect_url' => 'Expiration Redirect URL',
'expiration_redirect_url_helper' => 'Fallback URL to redirect to when the link is expired or inactive (leaves blank for 410 Gone error page).',
'form_section_validity' => 'Validity & Limits',
'use_date_validity' => 'Set Date Range Limits',
'notes' => 'Internal Notes',
'ga_tracking_id' => 'Google Analytics 4 Measurement ID',
'ga_tracking_id_helper' => 'Optional G-XXXXXXXXXX ID to track redirects server-side.',
@@ -106,6 +113,13 @@ return [
'action_stats' => 'Statistics',
'action_copy' => 'Copy URL',
'action_qr' => 'QR Code',
'action_edit' => 'Edit URL',
'action_delete' => 'Delete URL',
'action_share' => 'Share Link',
'share_title' => 'Share Link',
'share_description' => 'Share this short link via:',
'share_copy' => 'Copy',
'share_copied' => 'Short link copied to clipboard!',
// Stats Page
'stats_title' => 'Statistics',
@@ -153,6 +167,8 @@ return [
'settings_section_ga4' => 'GA4 Measurement Protocol',
'settings_ga4_description' => 'Configure server-side Google Analytics 4 event tracking via the Measurement Protocol. Events are sent in the background without blocking the redirect.',
'settings_site_name' => 'Site Name Override',
'settings_site_name_helper' => 'Custom brand/site name displayed on redirect prompt screens. If empty, falls back to config("app.name").',
'settings_route_prefix' => 'Route Prefix',
'settings_route_prefix_helper' => 'URL segment before the short key, e.g. "/s/abc123". Change requires a config:clear.',
'settings_key_length' => 'Auto-generated Key Length',
@@ -175,9 +191,197 @@ return [
'settings_geoip_timeout_helper' => 'Maximum seconds to wait for an external Geo-IP API response before giving up.',
'settings_maxmind_path' => 'MaxMind Database Path',
'settings_maxmind_path_helper' => 'Absolute path to your GeoLite2-Country.mmdb or GeoIP2-Country.mmdb file. Required when driver is set to MaxMind.',
'settings_maxmind_verify' => 'Verify file',
'settings_maxmind_verify_ok' => '✅ File found & readable',
'settings_maxmind_verify_fail' => '❌ File not found or not readable',
'settings_maxmind_verify_empty' => 'Please enter a path first.',
'settings_ga4_api_secret' => 'Measurement Protocol API Secret',
'settings_ga4_api_secret_helper' => 'Generate this in GA4 → Admin → Data Streams → your stream → Measurement Protocol API secrets.',
'settings_ga4_firebase_app_id' => 'Firebase App ID (optional)',
'settings_ga4_firebase_app_id_helper' => 'Required only if tracking a Firebase / app stream. Leave empty for standard web GA4 streams.',
'settings_ga4_verify' => 'Test connection',
'settings_ga4_verify_ok' => '✅ API Secret is valid — GA4 connection successful',
'settings_ga4_verify_fail' => '❌ Invalid API Secret — GA4 rejected the request',
'settings_ga4_verify_empty' => 'Please enter an API Secret first.',
'settings_ga4_verify_error' => '⚠️ Connection error — could not reach GA4',
'settings_section_buffering' => 'Visit Counters Buffering',
'settings_buffering_enabled' => 'Buffer Visit Counts in Cache',
'settings_buffering_helper' => 'When enabled, visit count increments are temporarily buffered in the application cache and must be flushed periodically to the database via "php artisan short-url:sync-counters". This prevents row-locking issues and performance degradation under high-traffic spikes.',
// CDN Trust Settings
'settings_trust_cdn_headers' => 'Trust CDN & Proxy Headers',
'settings_trust_cdn_headers_helper' => 'Enable this if your app sits behind a CDN (like Cloudflare, AWS CloudFront) or a reverse proxy. This allows extracting the real client IP and country code from CDN headers. Warning: only enable this if you are actually behind a proxy, otherwise client IP addresses can be spoofed!',
// Stats View & Export Localization
'stats_filter_visited_from' => 'Visited From',
'stats_filter_visited_until' => 'Visited Until',
'stats_action_export' => 'Export CSV',
'stats_csv_time' => 'Time',
'stats_csv_ip' => 'IP Address',
'stats_csv_country' => 'Country',
'stats_csv_device' => 'Device',
'stats_csv_browser' => 'Browser',
'stats_csv_os' => 'OS',
'stats_csv_referer' => 'Referer',
// Bulk Actions Localization
'action_enable_selected' => 'Enable selected',
'action_disable_selected' => 'Disable selected',
// Form Sections Localization
'form_section_options' => 'Options',
'form_section_notes' => 'Internal Notes',
'form_section_tracking' => 'Visit Tracking',
'form_section_tracked_fields' => 'Tracked Fields',
'form_section_analytics' => 'Third-Party Analytics',
// New Dashboard Analytics Keys
'stats_card_top_source' => 'Top UTM Source',
'stats_card_top_country' => 'Top Country',
'stats_filter_date_range' => 'Date Range',
'stats_preset_24_hours' => 'Last 24 Hours',
'stats_preset_7_days' => 'Last 7 Days',
'stats_preset_30_days' => 'Last 30 Days',
'stats_preset_90_days' => 'Last 90 Days',
'stats_preset_custom' => 'Custom Range',
'stats_breakdown_cities' => 'Top Cities',
'stats_no_city_data' => 'No city data.',
'stats_breakdown_utm_source' => 'Campaign Sources',
'stats_breakdown_utm_medium' => 'Campaign Mediums',
'stats_breakdown_utm_campaign' => 'Campaign Names',
'stats_no_utm_data' => 'No UTM data recorded.',
// New Targeting & Security Tab and fields
'tab_targeting' => 'Targeting & Security',
'security_section_title' => 'Security Controls',
'password' => 'Access Password',
'password_helper' => 'Require visitors to enter a password before being redirected.',
'show_warning_page' => 'Show Redirect Warning Page',
'show_warning_page_helper' => 'Show an intermediate screen warning visitors about external redirection (NSFW/phishing protection).',
'targeting_type' => 'Targeting Strategy',
'targeting_type_none' => 'None (Direct Redirect)',
'targeting_type_device' => 'Device-Based Redirects',
'targeting_type_country' => 'Country-Based (Geo-IP) Redirects',
'targeting_type_rotation' => 'A/B Split Rotation',
'device_targeting_rules' => 'Device Rules',
'country_targeting_rules' => 'Country Rules',
'rotation_targeting_rules' => 'Rotation Targets',
'device_mobile' => 'Mobile Destination URL',
'device_tablet' => 'Tablet Destination URL',
'device_desktop' => 'Desktop Destination URL',
'country_code' => 'Country Code',
'rotation_url' => 'Destination URL',
'rotation_weight' => 'Traffic Weight',
'rotation_weight_helper' => 'Percentage of traffic to route to this URL (e.g. 50 for 50%). Weights are balanced proportionally.',
// New Settings Page Fields
'settings_tab_advanced' => 'Performance & Security',
'settings_section_aggregation' => 'High-Traffic Log Management',
'settings_retention_days' => 'Raw Log Retention Period',
'settings_retention_days_helper' => 'Select the duration for which you want to keep detailed raw click logs before they are deleted.',
'settings_aggregation_enabled' => 'Enable Automatic Daily Pruning & Aggregation',
'settings_aggregation_enabled_helper' => 'When enabled, the plugin automatically registers a daily task in the scheduler (at 02:00) to aggregate visits into daily statistics and delete raw logs older than the chosen retention period.',
'retention_30_days' => '30 Days',
'retention_60_days' => '60 Days',
'retention_90_days' => '90 Days',
'retention_180_days' => '180 Days (Half Year)',
'retention_365_days' => '365 Days (1 Year)',
'retention_730_days' => '2 Years',
'settings_section_rate_limiting' => 'Rate Limiting / Bot Protection',
'settings_rate_limiting_enabled' => 'Enable Limit Protection',
'settings_rate_limiting_enabled_helper' => 'Limit the rate of redirects per client IP address.',
'settings_rate_limiting_max_attempts' => 'Max Redirects Allowed',
'settings_rate_limiting_max_attempts_helper' => 'Maximum allowed redirection requests within the decay window.',
'settings_rate_limiting_decay_seconds' => 'Decay Window (Seconds)',
'settings_rate_limiting_decay_seconds_helper' => 'Time period for the rate limiter.',
// Queue Settings Additions
'settings_queue_name' => 'Queue Name',
'settings_queue_name_helper' => 'The target queue to which tracking and buffering sync jobs are dispatched. Default: "default".',
'settings_geoip_stats_cache_ttl' => 'Stats Dashboard Cache TTL',
'settings_geoip_stats_cache_ttl_helper' => 'Number of seconds to cache query metrics on the dashboard statistics page (prevents database load). Default: 300 (5 minutes).',
// Default Tracking Tab
'settings_tab_tracking_defaults' => 'Default Tracking',
'settings_section_tracking_defaults' => 'Default Visitor Tracking Settings',
'settings_section_tracking_defaults_helper' => 'These settings govern the default tracking status for newly created short URLs.',
'settings_track_visits_default' => 'Enable Tracking by Default',
'settings_track_ip_default' => 'Default IP Address Tracking',
'settings_track_browser_default' => 'Default Browser Tracking',
'settings_track_browser_version_default' => 'Default Browser Version Tracking',
'settings_track_os_default' => 'Default OS Tracking',
'settings_track_os_version_default' => 'Default OS Version Tracking',
'settings_track_referer_default' => 'Default Referer URL Tracking',
'settings_track_device_type_default' => 'Default Device Type Tracking',
// QR Defaults Tab
'settings_tab_qr' => 'QR Defaults',
'settings_section_qr_defaults' => 'Default QR Code Design Options',
'settings_section_qr_defaults_helper' => 'Configure standard design styling automatically loaded for newly generated QR codes.',
'settings_qr_size' => 'Default Size (px)',
'settings_qr_margin' => 'Default Margin',
'settings_qr_dot_style' => 'Default Dot Style',
'settings_qr_foreground_color' => 'Default Foreground Color',
'settings_qr_background_color' => 'Default Background Color',
'settings_qr_gradient_enabled' => 'Enable Gradient by Default',
'settings_qr_gradient_from' => 'Gradient Color From',
'settings_qr_gradient_to' => 'Gradient Color To',
'settings_qr_gradient_type' => 'Default Gradient Type',
// Views
'password_title' => 'Password Required',
'password_description' => 'This link is password-protected. Please enter the correct password to continue.',
'password_placeholder' => 'Enter password',
'password_btn_unlock' => 'Unlock & Redirect',
'password_error' => 'Incorrect password.',
'warning_title' => 'Security Redirect Warning',
'warning_description' => 'You are leaving this secure portal and being redirected to an external target link. Please ensure you trust the address below:',
'warning_btn_continue' => 'Continue to Destination',
'warning_btn_back' => 'Go Back',
'pixel_loading_title' => 'Connecting...',
'pixel_loading_description' => 'Preparing your connection and forwarding you now.',
// Marketing & API Tab
'tab_marketing' => 'Marketing & API',
'marketing_pixels_title' => 'Retargeting Pixels (Client-Side)',
'marketing_pixels_desc' => 'Add ad tracking scripts to capture visitor cookies and build remarketing lists.',
'pixel_meta' => 'Meta Pixel ID',
'pixel_google' => 'Google Tag / GA4 ID',
'pixel_linkedin' => 'LinkedIn Partner ID',
'marketing_webhooks_title' => 'Link Webhook Integration',
'marketing_webhooks_desc' => 'Configure a custom destination URL to send a real-time HTTP POST notification on each click.',
'webhook_url' => 'Dedicated Webhook URL',
// Settings tab additions
'settings_tab_developer' => 'API & Webhooks',
'settings_section_rest_api' => 'REST API Access',
'settings_api_enabled' => 'Enable Developer REST API',
'settings_api_enabled_helper' => 'Allow external systems to create, list, and delete short URLs via the REST API. Disable to block all /api/short-url/* endpoints with a 503 response.',
'settings_section_global_webhook' => 'Global Webhook Configuration',
'settings_global_webhook_url' => 'Global Webhook URL',
'settings_global_webhook_url_helper' => 'Destination URL to dispatch event payloads asynchronously in the background for all links.',
'settings_webhook_events' => 'Monitored Webhook Events',
'settings_webhook_events_helper' => 'Select which events should trigger a POST notification.',
'webhook_event_visited' => 'Link Visited (Click)',
'webhook_event_created' => 'Link Created',
'webhook_event_expired' => 'Link Expired (Date)',
'webhook_event_limit_reached' => 'Link Click Limit Reached',
'settings_section_api_keys' => 'Developer API Keys',
'settings_api_keys_description' => 'Manage API keys to integrate with external systems (e.g. CRM, Zapier, Make). Authenticate requests using the X-Api-Key header.',
'settings_api_keys' => 'Active API Keys',
'api_key_name' => 'Key Name (Description)',
'api_key' => 'API Key',
'active' => 'Active',
// World Map Widget
'world_map_title' => 'Visitor World Map',
'world_map_total_clicks' => 'total clicks',
'world_map_countries' => 'countries',
'world_map_fewer' => 'Fewer',
'world_map_more' => 'More',
'world_map_top_countries' => 'Top Countries',
'world_map_no_data' => 'No geographic data yet.',
'world_map_no_data_sub' => 'Enable Geo-IP detection to start recording visitor locations.',
];

View File

@@ -0,0 +1,253 @@
<?php
return [
'AF' => 'Afganistan',
'AX' => 'Wyspy Alandzkie',
'AL' => 'Albania',
'DZ' => 'Algieria',
'AS' => 'Samoa Amerykańskie',
'AD' => 'Andora',
'AO' => 'Angola',
'AI' => 'Anguilla',
'AQ' => 'Antarktyda',
'AG' => 'Antigua i Barbuda',
'AR' => 'Argentyna',
'AM' => 'Armenia',
'AW' => 'Aruba',
'AU' => 'Australia',
'AT' => 'Austria',
'AZ' => 'Azerbejdżan',
'BS' => 'Bahamy',
'BH' => 'Bahrajn',
'BD' => 'Bangladesz',
'BB' => 'Barbados',
'BY' => 'Białoruś',
'BE' => 'Belgia',
'BZ' => 'Belize',
'BJ' => 'Benin',
'BM' => 'Bermudy',
'BT' => 'Bhutan',
'BO' => 'Boliwia',
'BQ' => 'Bonaire, Sint Eustatius i Saba',
'BA' => 'Bośnia i Hercegowina',
'BW' => 'Botswana',
'BV' => 'Wyspa Bouveta',
'BR' => 'Brazylia',
'IO' => 'Brytyjskie Terytorium Oceanu Indyjskiego',
'BN' => 'Brunei',
'BG' => 'Bułgaria',
'BF' => 'Burkina Faso',
'BI' => 'Burundi',
'CV' => 'Cabo Verde',
'KH' => 'Kambodża',
'CM' => 'Kamerun',
'CA' => 'Kanada',
'KY' => 'Kajmany',
'CF' => 'Republika Środkowoafrykańska',
'TD' => 'Czad',
'CL' => 'Chile',
'CN' => 'Chiny',
'CX' => 'Wyspa Bożego Narodzenia',
'CC' => 'Wyspy Kokosowe',
'CO' => 'Kolumbia',
'KM' => 'Komory',
'CD' => 'Demokratyczna Republika Konga',
'CG' => 'Kongo',
'CK' => 'Wyspy Cooka',
'CR' => 'Kostaryka',
'CI' => 'Wybrzeże Kości Słoniowej',
'HR' => 'Chorwacja',
'CU' => 'Kuba',
'CW' => 'Curaçao',
'CY' => 'Cypr',
'CZ' => 'Czechy',
'DK' => 'Dania',
'DJ' => 'Dżibuti',
'DM' => 'Dominika',
'DO' => 'Dominikana',
'EC' => 'Ekwador',
'EG' => 'Egipt',
'SV' => 'Salwador',
'GQ' => 'Gwinea Równikowa',
'ER' => 'Erytrea',
'EE' => 'Estonia',
'SZ' => 'Eswatini',
'ET' => 'Etiopia',
'FK' => 'Falklandy',
'FO' => 'Wyspy Owcze',
'FJ' => 'Fidżi',
'FI' => 'Finlandia',
'FR' => 'Francja',
'GF' => 'Gujana Francuska',
'PF' => 'Polinezja Francuska',
'TF' => 'Francuskie Terytoria Południowe',
'GA' => 'Gabon',
'GM' => 'Gambia',
'GE' => 'Gruzja',
'DE' => 'Niemcy',
'GH' => 'Ghana',
'GI' => 'Gibraltar',
'GR' => 'Grecja',
'GL' => 'Grenlandia',
'GD' => 'Grenada',
'GP' => 'Gwadelupa',
'GU' => 'Guam',
'GT' => 'Gwatemala',
'GG' => 'Guernsey',
'GN' => 'Gwinea',
'GW' => 'Gwinea Bissau',
'GY' => 'Gujana',
'HT' => 'Haiti',
'HM' => 'Wyspy Heard i McDonalda',
'VA' => 'Watykan',
'HN' => 'Honduras',
'HK' => 'Hongkong',
'HU' => 'Węgry',
'IS' => 'Islandia',
'IN' => 'Indie',
'ID' => 'Indonezja',
'IR' => 'Iran',
'IQ' => 'Irak',
'IE' => 'Irlandia',
'IM' => 'Wyspa Man',
'IL' => 'Izrael',
'IT' => 'Włochy',
'JM' => 'Jamajka',
'JP' => 'Japonia',
'JE' => 'Jersey',
'JO' => 'Jordania',
'KZ' => 'Kazachstan',
'KE' => 'Kenia',
'KI' => 'Kiribati',
'KP' => 'Korea Północna',
'KR' => 'Korea Południowa',
'KW' => 'Kuwejt',
'KG' => 'Kirgistan',
'LA' => 'Laos',
'LV' => 'Łotwa',
'LB' => 'Liban',
'LS' => 'Lesotho',
'LR' => 'Liberia',
'LY' => 'Libia',
'LI' => 'Liechtenstein',
'LT' => 'Litwa',
'LU' => 'Luksemburg',
'MO' => 'Makau',
'MG' => 'Madagaskar',
'MW' => 'Malawi',
'MY' => 'Malezja',
'MV' => 'Malediwy',
'ML' => 'Mali',
'MT' => 'Malta',
'MH' => 'Wyspy Marshalla',
'MQ' => 'Martynika',
'MR' => 'Mauretania',
'MU' => 'Mauritius',
'YT' => 'Majotta',
'MX' => 'Meksyk',
'FM' => 'Mikronezja',
'MD' => 'Mołdawia',
'MC' => 'Monako',
'MN' => 'Mongolia',
'ME' => 'Czarnogóra',
'MS' => 'Montserrat',
'MA' => 'Maroko',
'MZ' => 'Mozambik',
'MM' => 'Mjanma',
'NA' => 'Namibia',
'NR' => 'Nauru',
'NP' => 'Nepal',
'NL' => 'Holandia',
'NC' => 'Nowa Kaledonia',
'NZ' => 'Nowa Zelandia',
'NI' => 'Nikaragua',
'NE' => 'Niger',
'NG' => 'Nigeria',
'NU' => 'Niue',
'NF' => 'Norfolk',
'MK' => 'Macedonia Północna',
'MP' => 'Mariany Północne',
'NO' => 'Norwegia',
'OM' => 'Oman',
'PK' => 'Pakistan',
'PW' => 'Palau',
'PS' => 'Palestyna',
'PA' => 'Panama',
'PG' => 'Papua-Nowa Gwinea',
'PY' => 'Paragwaj',
'PE' => 'Peru',
'PH' => 'Filipiny',
'PN' => 'Pitcairn',
'PL' => 'Polska',
'PT' => 'Portugalia',
'PR' => 'Portoryko',
'QA' => 'Katar',
'RE' => 'Reunion',
'RO' => 'Rumunia',
'RU' => 'Rosja',
'RW' => 'Rwanda',
'BL' => 'Saint-Barthélemy',
'SH' => 'Święta Helena, Wyspa Wniebowstąpienia i Tristan da Cunha',
'KN' => 'Saint Kitts i Nevis',
'LC' => 'Saint Lucia',
'MF' => 'Saint-Martin',
'PM' => 'Saint-Pierre i Miquelon',
'VC' => 'Saint Vincent i Grenadyny',
'WS' => 'Samoa',
'SM' => 'San Marino',
'ST' => 'Wyspy Świętego Tomasza i Książęca',
'SA' => 'Arabia Saudyjska',
'SN' => 'Senegal',
'RS' => 'Serbia',
'SC' => 'Seszele',
'SL' => 'Sierra Leone',
'SG' => 'Singapur',
'SX' => 'Sint Maarten',
'SK' => 'Słowacja',
'SI' => 'Słowenia',
'SB' => 'Wyspy Salomona',
'SO' => 'Somalia',
'ZA' => 'Południowa Afryka',
'GS' => 'Georgia Południowa i Sandwich Południowy',
'SS' => 'Sudan Południowy',
'ES' => 'Hiszpania',
'LK' => 'Sri Lanka',
'SD' => 'Sudan',
'SR' => 'Surinam',
'SJ' => 'Svalbard i Jan Mayen',
'SE' => 'Szwecja',
'CH' => 'Szwajcaria',
'SY' => 'Syria',
'TW' => 'Tajwan',
'TJ' => 'Tadżykistan',
'TZ' => 'Tanzania',
'TH' => 'Tajlandia',
'TL' => 'Timor Wschodni',
'TG' => 'Togo',
'TK' => 'Tokelau',
'TO' => 'Tonga',
'TT' => 'Trynidad i Tobago',
'TN' => 'Tunezja',
'TR' => 'Turcja',
'TM' => 'Turkmenistan',
'TC' => 'Turks i Caicos',
'TV' => 'Tuvalu',
'UG' => 'Uganda',
'UA' => 'Ukraina',
'AE' => 'Zjednoczone Emiraty Arabskie',
'GB' => 'Wielka Brytania',
'UM' => 'Dalekie Wyspy Mniejsze Stanów Zjednoczonych',
'US' => 'Stany Zjednoczone',
'UY' => 'Urugwaj',
'UZ' => 'Uzbekistan',
'VU' => 'Vanuatu',
'VE' => 'Wenezuela',
'VN' => 'Wietnam',
'VG' => 'Brytyjskie Wyspy Dziewicze',
'VI' => 'Wyspy Dziewicze Stanów Zjednoczonych',
'WF' => 'Wallis i Futuna',
'EH' => 'Sahara Zachodnia',
'YE' => 'Jemen',
'ZM' => 'Zambia',
'ZW' => 'Zimbabwe',
];

View File

@@ -24,6 +24,13 @@ return [
'forward_query_params' => 'Przekaż parametry URL',
'forward_query_params_helper' => 'Dołącz parametry wejściowe (np. tagi UTM) do docelowego adresu URL.',
'expires_at' => 'Wygasa dnia',
'activated_at' => 'Aktywny od',
'max_visits' => 'Maksymalny limit wejść',
'max_visits_helper' => 'Opcjonalny limit liczby wejść, po osiągnięciu którego link zostanie automatycznie wyłączony.',
'expiration_redirect_url' => 'URL przekierowania po wygaśnięciu',
'expiration_redirect_url_helper' => 'Adres URL, na który nastąpi przekierowanie, gdy link wygaśnie lub będzie nieaktywny (pozostaw puste, aby wyświetlić błąd 410 Gone).',
'form_section_validity' => 'Ważność i limity',
'use_date_validity' => 'Ustaw limity datowe',
'notes' => 'Wewnętrzne notatki',
'ga_tracking_id' => 'Identyfikator śledzenia Google Analytics 4',
'ga_tracking_id_helper' => 'Opcjonalny identyfikator G-XXXXXXXXXX do śledzenia przekierowań po stronie serwera.',
@@ -106,6 +113,13 @@ return [
'action_stats' => 'Statystyki',
'action_copy' => 'Kopiuj link',
'action_qr' => 'Kod QR',
'action_edit' => 'Edytuj URL',
'action_delete' => 'Usuń URL',
'action_share' => 'Udostępnij link',
'share_title' => 'Udostępnij Link',
'share_description' => 'Udostępnij ten krótki link przez:',
'share_copy' => 'Skopiuj',
'share_copied' => 'Krótki link skopiowany do schowka!',
// Stats Page
'stats_title' => 'Statystyki',
@@ -154,6 +168,8 @@ return [
'settings_section_ga4' => 'GA4 Measurement Protocol',
'settings_ga4_description' => 'Skonfiguruj serwerowe śledzenie zdarzeń GA4 przez Measurement Protocol. Zdarzenia są wysyłane w tle bez blokowania przekierowania.',
'settings_site_name' => 'Niestandardowa nazwa witryny',
'settings_site_name_helper' => 'Własna nazwa witryny/marki wyświetlana na ekranach przekierowań (monit o hasło, ostrzeżenia, piksele). W przypadku braku wartości, zostanie użyta nazwa z konfiguracji config("app.name").',
'settings_route_prefix' => 'Prefiks trasy',
'settings_route_prefix_helper' => 'Segment URL przed kluczem, np. "/s/abc123". Zmiana wymaga php artisan config:clear.',
'settings_key_length' => 'Długość auto-generowanego klucza',
@@ -176,9 +192,187 @@ return [
'settings_geoip_timeout_helper' => 'Maksymalna liczba sekund oczekiwania na odpowiedź zewnętrznego API Geo-IP.',
'settings_maxmind_path' => 'Ścieżka bazy MaxMind',
'settings_maxmind_path_helper' => 'Bezwzględna ścieżka do pliku GeoLite2-Country.mmdb lub GeoIP2-Country.mmdb. Wymagana gdy sterownik to MaxMind.',
'settings_maxmind_verify' => 'Weryfikuj plik',
'settings_maxmind_verify_ok' => '✅ Plik znaleziony i dostępny',
'settings_maxmind_verify_fail' => '❌ Plik nie istnieje lub jest niedostępny',
'settings_maxmind_verify_empty' => 'Najpierw podaj ścieżkę do pliku.',
'settings_ga4_api_secret' => 'Klucz API Measurement Protocol',
'settings_ga4_api_secret_helper' => 'Wygeneruj w GA4 → Admin → Strumienie danych → twój strumień → Klucze API Measurement Protocol.',
'settings_ga4_firebase_app_id' => 'Firebase App ID (opcjonalne)',
'settings_ga4_firebase_app_id_helper' => 'Wymagane tylko przy śledzeniu strumienia Firebase/aplikacji. Zostaw puste dla standardowych strumieni GA4.',
'settings_ga4_verify' => 'Testuj połączenie',
'settings_ga4_verify_ok' => '✅ Klucz API jest prawidłowy — połączenie z GA4 udane',
'settings_ga4_verify_fail' => '❌ Nieprawidłowy klucz API — GA4 odrzuciło żądanie',
'settings_ga4_verify_empty' => 'Najpierw wprowadź klucz API.',
'settings_ga4_verify_error' => '⚠️ Błąd połączenia — nie można nawiązać kontaktu z GA4',
'settings_section_buffering' => 'Buforowanie liczników wizyt',
'settings_buffering_enabled' => 'Buforuj kliknięcia w pamięci podręcznej (Cache)',
'settings_buffering_helper' => 'Po włączeniu, zliczenia kliknięć będą buforowane w pamięci podręcznej aplikacji i muszą być okresowo synchronizowane z bazą danych za pomocą komendy "php artisan short-url:sync-counters". Zapobiega to blokowaniu wierszy bazy danych i spadkom wydajności przy masowym ruchu.',
// CDN Trust Settings
'settings_trust_cdn_headers' => 'Ufaj nagłówkom CDN i proxy',
'settings_trust_cdn_headers_helper' => 'Włącz tę opcję, jeśli Twoja aplikacja działa za CDN (np. Cloudflare, AWS CloudFront) lub reverse proxy. Pozwala to na pobieranie prawdziwego adresu IP klienta i kodu kraju z nagłówków CDN. Uwaga: włączaj tylko wtedy, gdy faktycznie korzystasz z proxy, w przeciwnym razie adresy IP mogą być sfałszowane!',
// Stats View & Export Localization
'stats_filter_visited_from' => 'Odwiedzono od',
'stats_filter_visited_until' => 'Odwiedzono do',
'stats_action_export' => 'Eksportuj CSV',
'stats_csv_time' => 'Czas',
'stats_csv_ip' => 'Adres IP',
'stats_csv_country' => 'Kraj',
'stats_csv_device' => 'Urządzenie',
'stats_csv_browser' => 'Przeglądarka',
'stats_csv_os' => 'System operacyjny',
'stats_csv_referer' => 'Źródło (Referer)',
// Bulk Actions Localization
'action_enable_selected' => 'Włącz zaznaczone',
'action_disable_selected' => 'Wyłącz zaznaczone',
// Form Sections Localization
'form_section_options' => 'Opcje',
'form_section_notes' => 'Wewnętrzne notatki',
'form_section_tracking' => 'Śledzenie wizyt',
'form_section_tracked_fields' => 'Śledzone pola',
'form_section_analytics' => 'Zewnętrzne systemy analityczne',
// New Dashboard Analytics Keys
'stats_card_top_source' => 'Główne źródło UTM',
'stats_card_top_country' => 'Główny kraj',
'stats_filter_date_range' => 'Zakres dat',
'stats_preset_24_hours' => 'Ostatnie 24 godziny',
'stats_preset_7_days' => 'Ostatnie 7 dni',
'stats_preset_30_days' => 'Ostatnie 30 dni',
'stats_preset_90_days' => 'Ostatnie 90 dni',
'stats_preset_custom' => 'Własny zakres',
'stats_breakdown_cities' => 'Najpopularniejsze miasta',
'stats_no_city_data' => 'Brak danych o miastach.',
'stats_breakdown_utm_source' => 'Źródła kampanii',
'stats_breakdown_utm_medium' => 'Media kampanii',
'stats_breakdown_utm_campaign' => 'Nazwy kampanii',
'stats_no_utm_data' => 'Brak danych o parametrach UTM.',
// New Targeting & Security Tab and fields
'tab_targeting' => 'Targetowanie i bezpieczeństwo',
'security_section_title' => 'Kontrola bezpieczeństwa',
'password' => 'Hasło dostępu',
'password_helper' => 'Wymagaj od odwiedzających wprowadzenia hasła przed przekierowaniem.',
'show_warning_page' => 'Pokaż stronę ostrzegającą przed przekierowaniem',
'show_warning_page_helper' => 'Pokaż ekran pośredni ostrzegający o przekierowaniu na zewnętrzny adres (ochrona przed phishingiem/bezpieczeństwo NSFW).',
'targeting_type' => 'Strategia targetowania',
'targeting_type_none' => 'Brak (Bezpośrednie przekierowanie)',
'targeting_type_device' => 'Przekierowania zależne od urządzenia',
'targeting_type_country' => 'Przekierowania zależne od kraju (Geo-IP)',
'targeting_type_rotation' => 'Podział ruchu A/B (Rotacja)',
'device_targeting_rules' => 'Reguły urządzeń',
'country_targeting_rules' => 'Reguły krajów',
'rotation_targeting_rules' => 'Cele rotacji',
'device_mobile' => 'Docelowy URL dla urządzeń mobilnych',
'device_tablet' => 'Docelowy URL dla tabletów',
'device_desktop' => 'Docelowy URL dla komputerów stacjonarnych',
'country_code' => 'Kod kraju',
'rotation_url' => 'Docelowy URL',
'rotation_weight' => 'Waga ruchu',
'rotation_weight_helper' => 'Procent ruchu kierowany na ten URL (np. 50 dla 50%). Wagi są bilansowane proporcjonalnie.',
// New Settings Page Fields
'settings_tab_advanced' => 'Wydajność i bezpieczeństwo',
'settings_section_aggregation' => 'Zarządzanie logami o dużym natężeniu ruchu',
'settings_retention_days' => 'Czas retencji surowych logów',
'settings_retention_days_helper' => 'Wybierz, przez jaki okres czasu chcesz przechowywać szczegółowe logi pojedynczych wizyt przed ich usunięciem.',
'settings_aggregation_enabled' => 'Włącz automatyczną agregację i czyszczenie logów',
'settings_aggregation_enabled_helper' => 'Gdy włączone, wtyczka automatycznie rejestruje zadanie w harmonogramie (codziennie o 02:00), aby zsumować wizyty do statystyk dziennych i usunąć surowe logi starsze niż wybrany okres retencji.',
'retention_30_days' => '30 dni',
'retention_60_days' => '60 dni',
'retention_90_days' => '90 dni',
'retention_180_days' => '180 dni (pół roku)',
'retention_365_days' => '365 dni (rok)',
'retention_730_days' => '2 lata',
'settings_section_rate_limiting' => 'Ograniczanie częstotliwości żądań / Ochrona przed botami',
'settings_rate_limiting_enabled' => 'Włącz ochronę limitów',
'settings_rate_limiting_enabled_helper' => 'Ograniczaj liczbę przekierowań na adres IP klienta.',
'settings_rate_limiting_max_attempts' => 'Maksymalna dopuszczalna liczba przekierowań',
'settings_rate_limiting_max_attempts_helper' => 'Maksymalna liczba żądań w oknie wygasania.',
'settings_rate_limiting_decay_seconds' => 'Okno wygasania (sekundy)',
'settings_rate_limiting_decay_seconds_helper' => 'Przedział czasowy dla ograniczenia liczby żądań.',
// Queue Settings Additions
'settings_queue_name' => 'Nazwa kolejki',
'settings_queue_name_helper' => 'Docelowa nazwa kolejki, do której wysyłane są zadania śledzenia i synchronizacji liczników. Domyślnie: "default".',
'settings_geoip_stats_cache_ttl' => 'TTL cache statystyk panelu',
'settings_geoip_stats_cache_ttl_helper' => 'Liczba sekund buforowania wyników zapytań na stronie statystyk (zapobiega obciążeniu bazy danych). Domyślnie: 300 (5 minut).',
// Default Tracking Tab
'settings_tab_tracking_defaults' => 'Domyślne śledzenie',
'settings_section_tracking_defaults' => 'Domyślne ustawienia śledzenia wizyt',
'settings_section_tracking_defaults_helper' => 'Ustawienia te określają domyślny status śledzenia dla nowo tworzonych krótkich adresów URL.',
'settings_track_visits_default' => 'Śledź wizyty domyślnie',
'settings_track_ip_default' => 'Domyślne śledzenie adresu IP',
'settings_track_browser_default' => 'Domyślne śledzenie przeglądarki',
'settings_track_browser_version_default' => 'Domyślne śledzenie wersji przeglądarki',
'settings_track_os_default' => 'Domyślne śledzenie systemu operacyjnego',
'settings_track_os_version_default' => 'Domyślne śledzenie wersji systemu operacyjnego',
'settings_track_referer_default' => 'Domyślne śledzenie adresu referera',
'settings_track_device_type_default' => 'Domyślne śledzenie typu urządzenia',
// QR Defaults Tab
'settings_tab_qr' => 'Domyślne QR',
'settings_section_qr_defaults' => 'Domyślne opcje wyglądu kodów QR',
'settings_section_qr_defaults_helper' => 'Skonfiguruj standardowy styl wyglądu automatycznie ładowany dla nowo generowanych kodów QR.',
'settings_qr_size' => 'Domyślny rozmiar (px)',
'settings_qr_margin' => 'Domyślny margines',
'settings_qr_dot_style' => 'Domyślny styl kropek',
'settings_qr_foreground_color' => 'Domyślny kolor pierwszego planu',
'settings_qr_background_color' => 'Domyślny kolor tła',
'settings_qr_gradient_enabled' => 'Domyślnie włącz gradient',
'settings_qr_gradient_from' => 'Kolor gradientu od',
'settings_qr_gradient_to' => 'Kolor gradientu do',
'settings_qr_gradient_type' => 'Domyślny typ gradientu',
// Views
'password_title' => 'Wymagane hasło',
'password_description' => 'Ten link jest chroniony hasłem. Wprowadź poprawne hasło, aby kontynuować.',
'password_placeholder' => 'Wpisz hasło',
'password_btn_unlock' => 'Odblokuj i przekieruj',
'password_error' => 'Nieprawidłowe hasło.',
'warning_title' => 'Ostrzeżenie o przekierowaniu',
'warning_description' => 'Opuszczasz ten bezpieczny portal i zostajesz przekierowany na zewnętrzny link docelowy. Upewnij się, że ufasz poniższemu adresowi:',
'warning_btn_continue' => 'Kontynuuj do celu',
'warning_btn_back' => 'Wróć',
'pixel_loading_title' => 'Łączenie...',
'pixel_loading_description' => 'Przygotowujemy połączenie i za chwilę zostaniesz przekierowany.',
// Marketing & API Tab
'tab_marketing' => 'Marketing i API',
'marketing_pixels_title' => 'Piksele retargetingowe (Client-Side)',
'marketing_pixels_desc' => 'Dodaj skrypty śledzące, aby dołączać ciasteczka odwiedzających i budować grupy remarketingowe reklam.',
'pixel_meta' => 'Meta Pixel ID',
'pixel_google' => 'Google Tag / GA4 ID',
'pixel_linkedin' => 'LinkedIn Partner ID',
'marketing_webhooks_title' => 'Integracja Webhook linku',
'marketing_webhooks_desc' => 'Skonfiguruj niestandardowy adres URL, pod który wysłane zostanie natychmiastowe powiadomienie HTTP POST po kliknięciu.',
'webhook_url' => 'Dedykowany Webhook URL',
// Settings tab additions
'settings_tab_developer' => 'API i Webhooki',
'settings_section_rest_api' => 'Dostęp do REST API',
'settings_api_enabled' => 'Włącz Developer REST API',
'settings_api_enabled_helper' => 'Zezwól zewnętrznym systemom na tworzenie, listowanie i usuwanie krótkich linków przez REST API. Wyłącz, aby zablokować wszystkie endpointy /api/short-url/* odpowiedzią 503.',
'settings_section_global_webhook' => 'Konfiguracja globalnego Webhooka',
'settings_global_webhook_url' => 'Globalny Webhook URL',
'settings_global_webhook_url_helper' => 'Adres URL, pod który wysyłane będą w tle powiadomienia o zdarzeniach ze wszystkich linków.',
'settings_webhook_events' => 'Monitorowane zdarzenia Webhooka',
'settings_webhook_events_helper' => 'Wybierz zdarzenia, które powinny wyzwalać wysłanie powiadomienia POST.',
'webhook_event_visited' => 'Odwiedziny linku (Wizyta)',
'webhook_event_created' => 'Utworzenie linku',
'webhook_event_expired' => 'Wygaśnięcie linku (Data)',
'webhook_event_limit_reached' => 'Osiągnięcie limitu kliknięć',
'settings_section_api_keys' => 'Klucze API Dewelopera',
'settings_api_keys_description' => 'Zarządzaj kluczami API do integracji z zewnętrznymi systemami (np. CRM, Zapier, Make). Autoryzacja odbywa się za pomocą nagłówka X-Api-Key.',
'settings_api_keys' => 'Aktywne klucze API',
'api_key_name' => 'Nazwa klucza (Opis)',
'api_key' => 'Klucz API',
'active' => 'Aktywny',
];

View File

@@ -0,0 +1,101 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="h-full">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ __('filament-short-url::default.password_title') ?? 'Password Protected' }}</title>
<!-- Premium Google Fonts: Bricolage Grotesque -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap" rel="stylesheet">
<!-- Self-contained Tailwind CSS CDN for maximum plug-and-play reliability -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Bricolage Grotesque', 'sans-serif'],
},
}
}
}
// Detect system dark mode preferences
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
</script>
</head>
<body class="bg-[#FCFCFC] dark:bg-[#0C0C0C] min-h-screen flex flex-col justify-between items-center py-10 px-6 font-sans antialiased">
@php
$logoPath = function_exists('setting') ? setting('logo_path') : null;
$logoUrl = $logoPath ? \Illuminate\Support\Facades\Storage::disk('public')->url($logoPath) : null;
$siteName = config('filament-short-url.site_name') ?: config('app.name', 'Laravel');
@endphp
{{-- Main Sign-in Box --}}
<div class="w-full max-w-[360px] flex flex-col items-center gap-6 my-auto">
<div class="flex flex-col items-center text-center pb-2 select-none w-full">
@if ($logoUrl)
<img src="{{ $logoUrl }}" alt="{{ $siteName }}" class="h-[60px] w-auto object-contain mb-4" />
@else
<span class="text-3xl font-extrabold tracking-tight text-neutral-900 dark:text-white mb-3">{{ $siteName }}</span>
@endif
<p class="text-xl font-medium text-neutral-900 dark:text-white mt-2">
{{ __('filament-short-url::default.password_title') ?? 'Password Protected' }}
</p>
<p class="text-sm text-neutral-400 dark:text-neutral-500 mt-1">
{{ __('filament-short-url::default.password_description') ?? 'This link is password-protected. Please enter the correct password to continue.' }}
</p>
</div>
<form method="POST" class="w-full flex flex-col gap-4">
@csrf
{{-- Password input styled exactly like Custom Login --}}
<div class="flex flex-col gap-1.5 w-full">
<div class="relative flex flex-col justify-center px-3 py-2 w-full rounded-xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 focus-within:ring-2 focus-within:ring-neutral-900 dark:focus-within:ring-white transition duration-200">
<label for="password" class="text-[10px] font-bold text-neutral-400 dark:text-neutral-500 uppercase tracking-wide select-none">
{{ __('filament-short-url::default.password_placeholder') ?? 'Password' }}
</label>
<input
type="password"
id="password"
name="password"
placeholder="••••••••"
required
autofocus
class="w-full bg-transparent text-sm text-neutral-900 dark:text-white placeholder-neutral-300 dark:placeholder-neutral-700 focus:outline-none py-0.5 mt-0.5"
/>
</div>
@if ($errors->has('password'))
<span class="text-xs text-red-500 px-1 mt-0.5">{{ $errors->first('password') }}</span>
@endif
</div>
{{-- Submit button --}}
<button
type="submit"
class="w-full mt-2 py-3.5 rounded-xl bg-neutral-900 hover:bg-neutral-800 dark:bg-white dark:hover:bg-neutral-200 dark:text-neutral-900 text-white font-semibold text-sm transition duration-200 shadow-sm flex justify-center items-center gap-2"
>
<span>{{ __('filament-short-url::default.password_btn_unlock') ?? 'Unlock & Redirect' }}</span>
<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
</svg>
</button>
</form>
</div>
{{-- Footer section --}}
<div class="flex flex-col items-center gap-2 mt-auto select-none">
<span class="text-xs font-medium text-neutral-400 dark:text-neutral-600">© {{ date('Y') }} {{ $siteName }} Inc. All rights reserved.</span>
</div>
</body>
</html>

View File

@@ -0,0 +1,136 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="h-full">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ __('filament-short-url::default.pixel_loading_title') ?? 'Connecting...' }}</title>
<!-- Premium Google Fonts: Bricolage Grotesque -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap" rel="stylesheet">
<!-- Self-contained Tailwind CSS CDN for maximum plug-and-play reliability -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Bricolage Grotesque', 'sans-serif'],
},
}
}
}
// Detect system dark mode preferences
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
</script>
<!-- Meta / Facebook Pixel -->
@if(!empty($pixelMetaId))
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '{{ $pixelMetaId }}');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id={{ $pixelMetaId }}&ev=PageView&noscript=1" /></noscript>
@endif
<!-- Google Analytics / GTM -->
@if(!empty($pixelGoogleId))
<script async src="https://www.googletagmanager.com/gtag/js?id={{ $pixelGoogleId }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '{{ $pixelGoogleId }}');
</script>
@endif
<!-- LinkedIn Insight -->
@if(!empty($pixelLinkedinId))
<script type="text/javascript">
_linkedin_data_partner_id = "{{ $pixelLinkedinId }}";
window._linkedin_data_partner_ids = window._linkedin_data_partner_ids || [];
window._linkedin_data_partner_ids.push(_linkedin_data_partner_id);
(function(l) {
if (!l){window.lintrk = function(a,b){window.lintrk.q.push([a,b])};
window.lintrk.q=[]}
var s = document.getElementsByTagName("script")[0];
var b = document.createElement("script");
b.type = "text/javascript";b.async = true;
b.src = "https://snap.licdn.com/li.lms-analytics/insight.min.js";
s.parentNode.insertBefore(b, s);})(window.lintrk);
</script>
<noscript><img height="1" width="1" style="display:none;" alt="" src="https://px.ads.linkedin.com/collect/?pid={{ $pixelLinkedinId }}&fmt=gif" /></noscript>
@endif
</head>
<body class="bg-[#FCFCFC] dark:bg-[#0C0C0C] min-h-screen flex flex-col justify-between items-center py-10 px-6 font-sans antialiased">
@php
$logoPath = function_exists('setting') ? setting('logo_path') : null;
$logoUrl = $logoPath ? \Illuminate\Support\Facades\Storage::disk('public')->url($logoPath) : null;
$siteName = config('filament-short-url.site_name') ?: config('app.name', 'Laravel');
@endphp
{{-- Main card --}}
<div class="w-full max-w-[360px] flex flex-col items-center gap-6 my-auto">
<div class="flex flex-col items-center text-center pb-2 select-none w-full">
@if ($logoUrl)
<img src="{{ $logoUrl }}" alt="{{ $siteName }}" class="h-[60px] w-auto object-contain mb-4" />
@else
<span class="text-3xl font-extrabold tracking-tight text-neutral-900 dark:text-white mb-3">{{ $siteName }}</span>
@endif
{{-- Animated spinner --}}
<div class="my-5 flex items-center justify-center gap-1.5" aria-hidden="true">
<span class="block w-2.5 h-2.5 rounded-full bg-neutral-300 dark:bg-neutral-600 animate-bounce [animation-delay:-0.3s]"></span>
<span class="block w-2.5 h-2.5 rounded-full bg-neutral-400 dark:bg-neutral-500 animate-bounce [animation-delay:-0.15s]"></span>
<span class="block w-2.5 h-2.5 rounded-full bg-neutral-500 dark:bg-neutral-400 animate-bounce"></span>
</div>
<p class="text-xl font-medium text-neutral-900 dark:text-white mt-2">
{{ __('filament-short-url::default.pixel_loading_title') ?? 'Connecting...' }}
</p>
<p class="text-sm text-neutral-400 dark:text-neutral-500 mt-1">
{{ __('filament-short-url::default.pixel_loading_description') ?? 'Preparing your connection and forwarding you now.' }}
</p>
</div>
{{-- Progress bar --}}
<div class="w-full h-1 rounded-full bg-neutral-200 dark:bg-neutral-800 overflow-hidden">
<div id="pixel-progress" class="h-full w-0 rounded-full bg-neutral-900 dark:bg-white transition-all ease-linear" style="transition-duration: 220ms;"></div>
</div>
</div>
{{-- Footer --}}
<div class="flex flex-col items-center gap-2 mt-auto select-none">
<span class="text-xs font-medium text-neutral-400 dark:text-neutral-600">© {{ date('Y') }} {{ $siteName }} Inc. All rights reserved.</span>
</div>
{{-- Redirect after pixels fire --}}
<script>
// Animate the progress bar to full in sync with the redirect delay
requestAnimationFrame(function() {
document.getElementById('pixel-progress').style.width = '100%';
});
setTimeout(function() {
window.location.replace("{!! addslashes($destination) !!}");
}, 250);
</script>
</body>
</html>

View File

@@ -108,6 +108,15 @@
background-color:#f3f4f6;
}
@keyframes qr-spin { to { transform: rotate(360deg); } }
.qr-margin-top {
margin-top: 12px !important;
}
.qr-space-y > div {
margin-top: 12px !important;
}
.qr-space-y > div:first-child {
margin-top: 0 !important;
}
</style>
{{-- Preload QR library as soon as the tab renders --}}
@@ -245,7 +254,7 @@
{{-- Size & Margin --}}
<div class="qr-section">
<div class="grid grid-cols-2 gap-3">
<div class="grid grid-cols-2 gap-3" style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:12px">
<div>
<span class="qr-label">{{ __('filament-short-url::default.qr_label_size') }}</span>
<input type="number" x-model.number="size" min="100" max="1000" step="10" class="qr-input-num" />
@@ -279,7 +288,7 @@
<span class="qr-label">{{ __('filament-short-url::default.qr_label_foreground_color') }}</span>
{{-- Mode radio --}}
<div class="flex gap-2">
<div class="flex gap-2" style="display:flex;gap:8px">
<button type="button"
:class="colorMode === 'solid' ? 'active' : ''"
class="qr-radio-option flex-1 justify-center text-center"
@@ -297,9 +306,9 @@
</div>
{{-- Single color picker --}}
<div x-show="colorMode === 'solid'" x-transition style="display:block" class="mt-3">
<div x-show="colorMode === 'solid'" x-transition style="display:block" class="mt-3 qr-margin-top">
<span class="qr-label">{{ __('filament-short-url::default.qr_label_color') }}</span>
<div class="flex items-center gap-2">
<div class="flex items-center gap-2" style="display:flex;align-items:center;gap:8px">
<div class="qr-color-swatch qr-color-picker" :style="'background:'+fgColor">
<input type="color" x-model="fgColor" />
</div>
@@ -311,11 +320,11 @@
</div>
{{-- Gradient pickers --}}
<div x-show="colorMode === 'gradient'" x-transition style="display:none" class="mt-3 space-y-3">
<div class="grid grid-cols-2 gap-2">
<div x-show="colorMode === 'gradient'" x-transition style="display:none" class="mt-3 space-y-3 qr-space-y qr-margin-top">
<div class="grid grid-cols-2 gap-2" style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:8px">
<div>
<span class="qr-label">{{ __('filament-short-url::default.qr_label_from') }}</span>
<div class="flex items-center gap-1.5">
<div class="flex items-center gap-1.5" style="display:flex;align-items:center;gap:6px">
<div class="qr-color-swatch qr-color-picker" :style="'background:'+gradientFrom">
<input type="color" x-model="gradientFrom" />
</div>
@@ -327,7 +336,7 @@
</div>
<div>
<span class="qr-label">{{ __('filament-short-url::default.qr_label_to') }}</span>
<div class="flex items-center gap-1.5">
<div class="flex items-center gap-1.5" style="display:flex;align-items:center;gap:6px">
<div class="qr-color-swatch qr-color-picker" :style="'background:'+gradientTo">
<input type="color" x-model="gradientTo" />
</div>
@@ -351,7 +360,7 @@
{{-- Background --}}
<div class="qr-section">
<span class="qr-label">{{ __('filament-short-url::default.qr_label_background') }}</span>
<div class="flex items-center justify-between">
<div class="flex items-center justify-between" style="display:flex;align-items:center;justify-content:space-between">
<span style="font-size:13px;font-weight:500;color:#374151" class="dark:text-gray-300">{{ __('filament-short-url::default.qr_label_transparent') }}</span>
<button type="button"
:class="bgTransparent ? 'on' : 'off'"
@@ -360,9 +369,9 @@
<span class="qr-toggle-thumb"></span>
</button>
</div>
<div x-show="!bgTransparent" x-transition style="display:block" class="mt-3">
<div x-show="!bgTransparent" x-transition style="display:block;margin-top:12px" class="mt-3 qr-margin-top">
<span class="qr-label">{{ __('filament-short-url::default.qr_label_color') }}</span>
<div class="flex items-center gap-2">
<div class="flex items-center gap-2" style="display:flex;align-items:center;gap:8px">
<div class="qr-color-swatch qr-color-picker" :style="'background:'+bgColor">
<input type="color" x-model="bgColor" />
</div>
@@ -372,8 +381,8 @@
maxlength="7" placeholder="#ffffff" />
</div>
</div>
<div x-show="bgTransparent" x-transition style="display:none" class="mt-3">
<div class="qr-checker flex h-9 w-full items-center justify-center rounded-lg border border-dashed border-gray-300" style="font-size:11px;color:#9ca3af;font-weight:600">
<div x-show="bgTransparent" x-transition style="display:none;margin-top:12px" class="mt-3 qr-margin-top">
<div class="qr-checker flex h-9 w-full items-center justify-center rounded-lg border border-dashed border-gray-300" style="display:flex;align-items:center;justify-content:center;font-size:11px;color:#9ca3af;font-weight:600">
TRANSPARENT
</div>
</div>
@@ -381,7 +390,7 @@
{{-- Eye Config --}}
<div class="qr-section">
<div class="flex items-center justify-between">
<div class="flex items-center justify-between" style="display:flex;align-items:center;justify-content:space-between">
<span class="qr-label" style="margin-bottom:0">{{ __('filament-short-url::default.qr_label_eye_config') }}</span>
<button type="button"
:class="eyeConfigEnabled ? 'on' : 'off'"
@@ -390,7 +399,7 @@
<span class="qr-toggle-thumb"></span>
</button>
</div>
<div x-show="eyeConfigEnabled" x-transition style="display:none" class="mt-3 space-y-3">
<div x-show="eyeConfigEnabled" x-transition style="display:none" class="mt-3 space-y-3 qr-space-y qr-margin-top">
<div>
<span class="qr-label">{{ __('filament-short-url::default.qr_label_eye_square_style') }}</span>
<select x-model="eyeSquareStyle" class="qr-select">
@@ -408,7 +417,7 @@
</div>
<div>
<span class="qr-label">{{ __('filament-short-url::default.qr_label_eye_color') }}</span>
<div class="flex items-center gap-2">
<div class="flex items-center gap-2" style="display:flex;align-items:center;gap:8px">
<div class="qr-color-swatch qr-color-picker" :style="'background:'+eyeColor">
<input type="color" x-model="eyeColor" />
</div>
@@ -427,9 +436,9 @@
<div style="display:flex;flex-direction:column;min-width:0;height:100%">
{{-- Top bar --}}
<div class="mb-4 flex items-center justify-between">
<div class="mb-4 flex items-center justify-between" style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px">
<span style="font-size:13px;font-weight:600;color:#9ca3af">{{ __('filament-short-url::default.qr_label_preview') }}</span>
<div class="flex items-center gap-2">
<div class="flex items-center gap-2" style="display:flex;align-items:center;gap:8px">
<button type="button" x-on:click="download('png')" class="qr-dl-btn">
<svg style="width:13px;height:13px" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"/>

View File

@@ -16,18 +16,54 @@
</x-filament::tabs.item>
</x-filament::tabs>
<div class="space-y-6">
@livewire(\Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlStatsOverview::class, ['record' => $record])
@php
$dateFrom = $this->filterData['date_from'] ?? null;
$dateTo = $this->filterData['date_to'] ?? null;
$isCustom = ($this->filterData['preset'] ?? '') === 'custom';
@endphp
<div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
<div class="lg:col-span-2">
@livewire(\Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlVisitsChart::class, ['record' => $record])
</div>
<div>
@livewire(\Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlVisitsRightBreakdown::class, ['record' => $record])
<div class="space-y-6">
<div class="flex justify-end items-center">
<div class="w-full {{ $isCustom ? 'max-w-xl' : 'max-w-[200px]' }}">
<form>
{{ $this->form }}
</form>
</div>
</div>
@livewire(\Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlVisitsBottomBreakdown::class, ['record' => $record])
@livewire(\Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlStatsOverview::class, [
'record' => $record,
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
], key('stats-overview-' . $dateFrom . '-' . $dateTo))
<div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
<div class="lg:col-span-2">
@livewire(\Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlVisitsChart::class, [
'record' => $record,
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
], key('stats-chart-' . $dateFrom . '-' . $dateTo))
</div>
<div>
@livewire(\Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlVisitsRightBreakdown::class, [
'record' => $record,
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
], key('stats-right-breakdown-' . $dateFrom . '-' . $dateTo))
</div>
</div>
@livewire(\Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlWorldMapWidget::class, [
'record' => $record,
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
], key('stats-world-map-' . $dateFrom . '-' . $dateTo))
@livewire(\Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlVisitsBottomBreakdown::class, [
'record' => $record,
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
], key('stats-bottom-breakdown-' . $dateFrom . '-' . $dateTo))
</div>
</x-filament-panels::page>

View File

@@ -0,0 +1,113 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="h-full">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ __('filament-short-url::default.warning_title') ?? 'Redirect Warning' }}</title>
<!-- Premium Google Fonts: Bricolage Grotesque -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap" rel="stylesheet">
<!-- Self-contained Tailwind CSS CDN for maximum plug-and-play reliability -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Bricolage Grotesque', 'sans-serif'],
},
}
}
}
// Detect system dark mode preferences
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
</script>
</head>
<body class="bg-[#FCFCFC] dark:bg-[#0C0C0C] min-h-screen flex flex-col justify-between items-center py-10 px-6 font-sans antialiased">
@php
$logoPath = function_exists('setting') ? setting('logo_path') : null;
$logoUrl = $logoPath ? \Illuminate\Support\Facades\Storage::disk('public')->url($logoPath) : null;
$siteName = config('filament-short-url.site_name') ?: config('app.name', 'Laravel');
@endphp
{{-- Main Warning Box --}}
<div class="w-full max-w-[360px] flex flex-col items-center gap-6 my-auto">
<div class="flex flex-col items-center text-center pb-2 select-none w-full">
@if ($logoUrl)
<img src="{{ $logoUrl }}" alt="{{ $siteName }}" class="h-[60px] w-auto object-contain mb-4" />
@else
<span class="text-3xl font-extrabold tracking-tight text-neutral-900 dark:text-white mb-3">{{ $siteName }}</span>
@endif
<p class="text-xl font-medium text-neutral-900 dark:text-white mt-2">
{{ __('filament-short-url::default.warning_title') ?? 'Security Redirect Warning' }}
</p>
<p class="text-sm text-neutral-400 dark:text-neutral-500 mt-1">
{{ __('filament-short-url::default.warning_description') ?? 'You are leaving this secure portal and being redirected to an external target link. Please ensure you trust the address below:' }}
</p>
</div>
<div class="w-full flex flex-col gap-4">
{{-- Destination URL Container styled exactly like Custom Login input box --}}
<div class="flex flex-col gap-1.5 w-full">
<div class="relative flex items-center justify-between px-3 py-3 w-full rounded-xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 transition duration-200">
<div class="flex-grow flex flex-col justify-center min-w-0 pr-4">
<span class="text-[10px] font-bold text-neutral-400 dark:text-neutral-500 uppercase tracking-wide select-none">
Destination URL
</span>
<p id="dest-url-text" class="break-all text-xs font-mono font-semibold text-rose-600 dark:text-rose-400 mt-1 select-all">
{{ $destinationUrl }}
</p>
</div>
<!-- Quick Copy Button -->
<button onclick="
const text = document.getElementById('dest-url-text').innerText;
navigator.clipboard.writeText(text);
const btn = this;
const origHtml = btn.innerHTML;
btn.innerHTML = `<svg class='h-4 w-4 text-emerald-500' fill='none' viewBox='0 0 24 24' stroke='currentColor' stroke-width='3.5'><path stroke-linecap='round' stroke-linejoin='round' d='M5 13l4 4L19 7' /></svg>`;
setTimeout(() => { btn.innerHTML = origHtml; }, 2000);
" class="flex-shrink-0 p-2 rounded-lg border border-neutral-200 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-950 text-neutral-400 hover:text-neutral-600 dark:text-neutral-500 dark:hover:text-neutral-300 transition-colors focus:outline-none" title="Copy URL">
<svg class="h-4 w-4 pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</button>
</div>
</div>
{{-- Action Buttons --}}
<div class="flex flex-col gap-3 w-full mt-2">
<!-- Continue Button (Primary Accent) -->
<a href="{{ request()->fullUrlWithQuery(['confirmed' => 1]) }}"
class="w-full py-3.5 rounded-xl bg-rose-600 hover:bg-rose-500 dark:bg-rose-500 dark:hover:bg-rose-400 text-white font-semibold text-sm transition duration-200 shadow-sm flex justify-center items-center gap-2 text-center">
<span>{{ __('filament-short-url::default.warning_btn_continue') ?? 'Continue to Destination' }}</span>
<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
</svg>
</a>
<!-- Go Back Button (Secondary) -->
<button onclick="window.history.back()"
class="w-full py-3 rounded-xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 hover:bg-neutral-50 dark:hover:bg-neutral-800 text-neutral-900 dark:text-white font-semibold text-sm transition duration-200 flex justify-center items-center gap-2 shadow-sm">
{{ __('filament-short-url::default.warning_btn_back') ?? 'Go Back' }}
</button>
</div>
</div>
</div>
{{-- Footer section --}}
<div class="flex flex-col items-center gap-2 mt-auto select-none">
<span class="text-xs font-medium text-neutral-400 dark:text-neutral-600">© {{ date('Y') }} {{ $siteName }} Inc. All rights reserved.</span>
</div>
</body>
</html>

View File

@@ -27,118 +27,231 @@
@endphp
<x-filament-widgets::widget>
<div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
<div class="space-y-6">
{{-- Row 1: Devices, Browsers, Operating Systems --}}
<div class="grid grid-cols-1 gap-6 md:grid-cols-3">
{{-- Devices --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-50 text-emerald-500 dark:bg-emerald-950/50 dark:text-emerald-400">
<x-filament::icon icon="heroicon-o-device-phone-mobile" class="h-5 w-5" />
{{-- Devices --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-50 text-emerald-500 dark:bg-emerald-950/50 dark:text-emerald-400">
<x-filament::icon icon="heroicon-o-device-phone-mobile" class="h-5 w-5" />
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_devices') }}</h3>
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_devices') }}</h3>
</div>
<div class="space-y-4">
@forelse ($visitsByDevice as $device => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center gap-3">
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-50 text-gray-500 dark:bg-gray-800 dark:text-gray-400">
<x-filament::icon :icon="$deviceIcons[$device] ?? 'heroicon-m-question-mark-circle'" class="h-4 w-4" />
<div class="space-y-4">
@forelse ($visitsByDevice as $device => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center gap-3">
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-50 text-gray-500 dark:bg-gray-800 dark:text-gray-400">
<x-filament::icon :icon="$deviceIcons[$device] ?? 'heroicon-m-question-mark-circle'" class="h-4 w-4" />
</div>
<div class="flex-1 min-w-0">
<div class="flex justify-between text-sm">
<span class="capitalize font-medium text-gray-700 dark:text-gray-300 truncate">{{ $device }}</span>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white">{{ $pct }}%</span>
</div>
<div class="mt-1.5 h-1.5 overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800">
<div class="h-full rounded-full bg-emerald-500 transition-all duration-500" style="width: {{ $pct }}%"></div>
</div>
</div>
</div>
<div class="flex-1 min-w-0">
<div class="flex justify-between text-sm">
<span class="capitalize font-medium text-gray-700 dark:text-gray-300 truncate">{{ $device }}</span>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white">{{ $pct }}%</span>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_device_data') }}</p>
@endforelse
</div>
</div>
{{-- Browsers --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-amber-50 text-amber-500 dark:bg-amber-950/50 dark:text-amber-400">
<x-filament::icon icon="heroicon-o-globe-asia-australia" class="h-5 w-5" />
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_browsers') }}</h3>
</div>
<div class="space-y-3.5">
@forelse ($visitsByBrowser as $browser => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center justify-between text-sm">
<div class="flex items-center gap-2 min-w-0">
<x-filament::icon :icon="$browserIcons[$browser] ?? 'heroicon-m-globe-alt'" class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" />
<span class="font-medium text-gray-700 dark:text-gray-300 truncate">{{ $browser }}</span>
</div>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white shrink-0 ml-2">
{{ number_format($count) }} <span class="text-gray-400 dark:text-gray-500">({{ $pct }}%)</span>
</span>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_browser_data') }}</p>
@endforelse
</div>
</div>
{{-- Operating Systems --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-50 text-blue-500 dark:bg-blue-950/50 dark:text-blue-400">
<x-filament::icon icon="heroicon-o-computer-desktop" class="h-5 w-5" />
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_os') }}</h3>
</div>
<div class="space-y-3.5">
@forelse ($visitsByOs as $os => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center justify-between text-sm">
<div class="flex items-center gap-2 min-w-0">
<x-filament::icon :icon="$osIcons[$os] ?? 'heroicon-m-computer-desktop'" class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" />
<span class="font-medium text-gray-700 dark:text-gray-300 truncate">{{ $os }}</span>
</div>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white shrink-0 ml-2">
{{ number_format($count) }} <span class="text-gray-400 dark:text-gray-500">({{ $pct }}%)</span>
</span>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_os_data') }}</p>
@endforelse
</div>
</div>
</div>
{{-- Row 2: Referrers, Cities --}}
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
{{-- Referers --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-purple-50 text-purple-500 dark:bg-purple-950/50 dark:text-purple-400">
<x-filament::icon icon="heroicon-o-link" class="h-5 w-5" />
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_referers') }}</h3>
</div>
<div class="space-y-3">
@forelse ($visitsByReferer as $referer => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center justify-between text-sm gap-4">
<div class="flex items-center gap-2 min-w-0 flex-1">
<x-filament::icon icon="heroicon-m-link" class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" />
@if ($referer === 'Direct')
<span class="font-medium text-gray-500 dark:text-gray-400 truncate">{{ $referer }}</span>
@else
<a href="https://{{ $referer }}" target="_blank" rel="noopener"
class="truncate text-indigo-600 hover:underline dark:text-indigo-400 font-medium">
{{ $referer }}
</a>
@endif
</div>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white shrink-0 ml-2">
{{ number_format($count) }} <span class="text-gray-400 dark:text-gray-500">({{ $pct }}%)</span>
</span>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_referer_data') }}</p>
@endforelse
</div>
</div>
{{-- Cities --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-50 text-emerald-500 dark:bg-emerald-950/50 dark:text-emerald-400">
<x-filament::icon icon="heroicon-o-map-pin" class="h-5 w-5" />
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_cities') }}</h3>
</div>
<div class="space-y-3">
@forelse ($visitsByCity as $city => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div>
<div class="flex items-center justify-between text-sm">
<span class="font-medium text-gray-700 dark:text-gray-300">{{ $city }}</span>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white">{{ number_format($count) }} <span class="text-gray-400 dark:text-gray-500">({{ $pct }}%)</span></span>
</div>
<div class="mt-1.5 h-1.5 overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800">
<div class="h-full rounded-full bg-emerald-500 transition-all duration-500" style="width: {{ $pct }}%"></div>
</div>
</div>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_device_data') }}</p>
@endforelse
</div>
</div>
{{-- Browsers --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-amber-50 text-amber-500 dark:bg-amber-950/50 dark:text-amber-400">
<x-filament::icon icon="heroicon-o-globe-asia-australia" class="h-5 w-5" />
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_city_data') }}</p>
@endforelse
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_browsers') }}</h3>
</div>
<div class="space-y-3.5">
@forelse ($visitsByBrowser as $browser => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center justify-between text-sm">
<div class="flex items-center gap-2 min-w-0">
<x-filament::icon :icon="$browserIcons[$browser] ?? 'heroicon-m-globe-alt'" class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" />
<span class="font-medium text-gray-700 dark:text-gray-300 truncate">{{ $browser }}</span>
</div>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white shrink-0 ml-2">
{{ number_format($count) }} <span class="text-gray-400 dark:text-gray-500">({{ $pct }}%)</span>
</span>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_browser_data') }}</p>
@endforelse
</div>
</div>
{{-- Operating Systems --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-50 text-blue-500 dark:bg-blue-950/50 dark:text-blue-400">
<x-filament::icon icon="heroicon-o-computer-desktop" class="h-5 w-5" />
{{-- UTM Campaigns Section --}}
<div class="grid grid-cols-1 gap-6 md:grid-cols-3">
{{-- UTM Sources --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-rose-50 text-rose-500 dark:bg-rose-950/50 dark:text-rose-400">
<x-filament::icon icon="heroicon-o-megaphone" class="h-5 w-5" />
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_utm_source') }}</h3>
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_os') }}</h3>
</div>
<div class="space-y-3.5">
@forelse ($visitsByOs as $os => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center justify-between text-sm">
<div class="flex items-center gap-2 min-w-0">
<x-filament::icon :icon="$osIcons[$os] ?? 'heroicon-m-computer-desktop'" class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" />
<span class="font-medium text-gray-700 dark:text-gray-300 truncate">{{ $os }}</span>
<div class="space-y-3.5">
@forelse ($utmSources as $source => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center justify-between text-sm">
<span class="font-medium text-gray-700 dark:text-gray-300 truncate mr-2">{{ $source }}</span>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white shrink-0">
{{ number_format($count) }} <span class="text-gray-400 dark:text-gray-500">({{ $pct }}%)</span>
</span>
</div>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white shrink-0 ml-2">
{{ number_format($count) }} <span class="text-gray-400 dark:text-gray-500">({{ $pct }}%)</span>
</span>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_os_data') }}</p>
@endforelse
</div>
</div>
{{-- Referers --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-purple-50 text-purple-500 dark:bg-purple-950/50 dark:text-purple-400">
<x-filament::icon icon="heroicon-o-link" class="h-5 w-5" />
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_utm_data') }}</p>
@endforelse
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_referers') }}</h3>
</div>
<div class="space-y-3">
@forelse ($visitsByReferer as $referer => $count)
<div class="flex items-center justify-between text-sm gap-4">
<div class="flex items-center gap-2 min-w-0 flex-1">
<x-filament::icon icon="heroicon-m-link" class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" />
<a href="{{ $referer }}" target="_blank" rel="noopener"
class="truncate text-indigo-600 hover:underline dark:text-indigo-400 font-medium">
{{ $referer }}
</a>
</div>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white shrink-0">
{{ number_format($count) }}
</span>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_referer_data') }}</p>
@endforelse
</div>
</div>
{{-- UTM Mediums --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-teal-50 text-teal-500 dark:bg-teal-950/50 dark:text-teal-400">
<x-filament::icon icon="heroicon-o-tag" class="h-5 w-5" />
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_utm_medium') }}</h3>
</div>
<div class="space-y-3.5">
@forelse ($utmMediums as $medium => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center justify-between text-sm">
<span class="font-medium text-gray-700 dark:text-gray-300 truncate mr-2">{{ $medium }}</span>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white shrink-0">
{{ number_format($count) }} <span class="text-gray-400 dark:text-gray-500">({{ $pct }}%)</span>
</span>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_utm_data') }}</p>
@endforelse
</div>
</div>
{{-- UTM Campaigns --}}
<div class="fi-wi-stats-breakdown-card rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md dark:border-gray-800 dark:bg-gray-900/50">
<div class="mb-4 flex items-center gap-3 border-b border-gray-100 pb-3 dark:border-gray-800">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-cyan-50 text-cyan-500 dark:bg-cyan-950/50 dark:text-cyan-400">
<x-filament::icon icon="heroicon-o-flag" class="h-5 w-5" />
</div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ __('filament-short-url::default.stats_breakdown_utm_campaign') }}</h3>
</div>
<div class="space-y-3.5">
@forelse ($utmCampaigns as $campaign => $count)
@php $pct = $totalVisits > 0 ? round($count / $totalVisits * 100) : 0; @endphp
<div class="flex items-center justify-between text-sm">
<span class="font-medium text-gray-700 dark:text-gray-300 truncate mr-2">{{ $campaign }}</span>
<span class="font-mono text-xs font-semibold text-gray-900 dark:text-white shrink-0">
{{ number_format($count) }} <span class="text-gray-400 dark:text-gray-500">({{ $pct }}%)</span>
</span>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.stats_no_utm_data') }}</p>
@endforelse
</div>
</div>
</div>
</div>
</x-filament-widgets::widget>

View File

@@ -0,0 +1,403 @@
@php
/**
* World-map heat-map widget.
*
* Uses Natural Earth 110m simplified country paths (public-domain).
* Countries are coloured using their ISO-3166-1 alpha-2 code which is stored
* in the short_url_visits.country_code column.
*
* $countryData array<ISO2, int> raw click counts
* $normalized array<ISO2, 0-100> intensity percentage
* $maxCount int
* $totalClicks int
*/
/**
* Very compact "mercator" paths for ~180 countries sourced from public-domain
* Natural Earth data (110m resolution) encoded into a 950×500 viewport.
*
* Only the most visited countries are listed for performance; the rest render
* in a neutral colour. Full-resolution SVG world maps can be bundled as an
* asset if needed.
*/
$countryPaths = [
'AF' => 'M 613 175 L 617 170 L 626 172 L 630 168 L 637 173 L 638 180 L 633 186 L 624 189 L 616 184 Z',
'AL' => 'M 508 142 L 511 138 L 514 142 L 512 147 L 508 145 Z',
'DZ' => 'M 470 148 L 500 148 L 500 185 L 470 185 L 455 175 L 455 158 Z',
'AO' => 'M 500 240 L 520 240 L 520 270 L 500 270 L 490 255 Z',
'AR' => 'M 265 330 L 280 320 L 285 360 L 275 400 L 260 410 L 250 390 L 255 350 Z',
'AU' => 'M 730 310 L 790 295 L 820 310 L 830 345 L 810 370 L 760 375 L 725 355 L 720 330 Z',
'AT' => 'M 500 120 L 514 118 L 516 124 L 502 126 Z',
'AZ' => 'M 568 138 L 575 134 L 580 140 L 574 145 L 568 142 Z',
'BD' => 'M 655 180 L 663 178 L 666 185 L 660 190 L 654 187 Z',
'BE' => 'M 480 112 L 487 110 L 489 116 L 482 118 Z',
'BF' => 'M 460 198 L 475 195 L 478 205 L 462 208 Z',
'BY' => 'M 530 105 L 545 103 L 548 112 L 532 115 Z',
'BJ' => 'M 475 205 L 480 202 L 482 215 L 477 218 Z',
'BO' => 'M 265 295 L 280 288 L 285 310 L 268 315 Z',
'BA' => 'M 507 130 L 514 128 L 515 136 L 508 137 Z',
'BW' => 'M 518 278 L 530 275 L 532 290 L 520 292 Z',
'BR' => 'M 255 220 L 320 210 L 340 240 L 330 300 L 290 320 L 255 310 L 235 280 L 240 250 Z',
'BN' => 'M 724 218 L 728 215 L 730 220 L 726 223 Z',
'BG' => 'M 525 130 L 536 128 L 537 136 L 526 137 Z',
'KH' => 'M 705 210 L 715 207 L 717 218 L 707 220 Z',
'CM' => 'M 490 210 L 503 207 L 505 230 L 491 232 Z',
'CA' => 'M 55 65 L 200 55 L 220 85 L 180 100 L 100 108 L 55 95 Z',
'CF' => 'M 502 220 L 520 218 L 522 235 L 504 237 Z',
'TD' => 'M 498 188 L 515 185 L 517 220 L 499 222 Z',
'CL' => 'M 250 295 L 258 290 L 260 380 L 252 385 L 248 350 Z',
'CN' => 'M 640 130 L 740 125 L 755 160 L 745 200 L 700 215 L 660 205 L 635 185 L 630 160 Z',
'CO' => 'M 225 220 L 255 215 L 260 250 L 240 258 L 220 245 Z',
'CD' => 'M 503 238 L 535 230 L 540 270 L 520 278 L 500 270 Z',
'CG' => 'M 496 238 L 505 236 L 507 255 L 497 257 Z',
'CR' => 'M 205 215 L 212 212 L 213 220 L 206 222 Z',
'HR' => 'M 505 126 L 514 124 L 514 132 L 506 133 Z',
'CU' => 'M 198 183 L 218 180 L 220 188 L 200 191 Z',
'CY' => 'M 540 152 L 548 150 L 549 155 L 541 156 Z',
'CZ' => 'M 505 115 L 518 113 L 519 120 L 506 121 Z',
'DK' => 'M 494 98 L 500 95 L 502 105 L 495 107 Z',
'DO' => 'M 225 188 L 233 186 L 234 193 L 226 194 Z',
'EC' => 'M 220 248 L 233 244 L 235 260 L 221 263 Z',
'EG' => 'M 537 158 L 558 155 L 560 175 L 538 178 Z',
'SV' => 'M 196 210 L 203 208 L 204 214 L 197 215 Z',
'GQ' => 'M 487 228 L 493 226 L 494 233 L 488 234 Z',
'ER' => 'M 553 192 L 563 188 L 565 198 L 554 200 Z',
'EE' => 'M 525 95 L 535 93 L 536 99 L 526 101 Z',
'ET' => 'M 545 205 L 570 198 L 574 220 L 548 228 Z',
'FJ' => 'M 865 285 L 873 282 L 875 290 L 867 292 Z',
'FI' => 'M 520 75 L 540 68 L 545 92 L 522 95 Z',
'FR' => 'M 467 115 L 492 112 L 494 133 L 469 136 Z',
'GA' => 'M 490 235 L 500 233 L 501 248 L 491 250 Z',
'GM' => 'M 430 200 L 442 198 L 443 204 L 431 205 Z',
'GE' => 'M 558 130 L 572 128 L 573 136 L 559 137 Z',
'DE' => 'M 491 105 L 512 103 L 514 125 L 492 127 Z',
'GH' => 'M 458 212 L 470 210 L 471 228 L 459 230 Z',
'GR' => 'M 519 138 L 533 136 L 535 150 L 520 152 Z',
'GT' => 'M 187 207 L 197 205 L 198 215 L 188 217 Z',
'GN' => 'M 432 210 L 452 207 L 454 222 L 433 225 Z',
'GW' => 'M 428 205 L 438 203 L 439 210 L 429 211 Z',
'GY' => 'M 265 230 L 275 227 L 277 242 L 267 244 Z',
'HT' => 'M 218 188 L 226 186 L 227 194 L 219 195 Z',
'HN' => 'M 197 208 L 212 205 L 213 215 L 198 217 Z',
'HU' => 'M 510 120 L 525 118 L 526 127 L 511 128 Z',
'IN' => 'M 617 160 L 660 155 L 665 195 L 655 215 L 635 220 L 615 205 L 608 185 Z',
'ID' => 'M 710 235 L 790 225 L 800 255 L 780 265 L 720 260 L 705 250 Z',
'IR' => 'M 573 148 L 615 142 L 620 172 L 608 185 L 578 180 L 568 165 Z',
'IQ' => 'M 557 148 L 580 145 L 582 170 L 558 173 Z',
'IE' => 'M 453 105 L 463 103 L 464 115 L 454 117 Z',
'IL' => 'M 545 155 L 550 153 L 551 163 L 546 165 Z',
'IT' => 'M 492 128 L 512 125 L 518 148 L 508 158 L 494 150 Z',
'CI' => 'M 445 215 L 462 212 L 463 228 L 446 231 Z',
'JP' => 'M 770 135 L 795 128 L 800 155 L 775 162 L 765 150 Z',
'JO' => 'M 548 155 L 557 153 L 558 162 L 549 163 Z',
'KZ' => 'M 580 108 L 645 103 L 650 140 L 640 145 L 582 142 Z',
'KE' => 'M 543 232 L 563 227 L 566 252 L 544 255 Z',
'KP' => 'M 751 140 L 763 137 L 765 150 L 752 152 Z',
'KR' => 'M 758 148 L 770 145 L 772 158 L 759 160 Z',
'XK' => 'M 513 133 L 519 131 L 520 137 L 514 138 Z',
'KW' => 'M 570 160 L 576 158 L 577 164 L 571 165 Z',
'KG' => 'M 630 130 L 648 127 L 650 136 L 631 138 Z',
'LA' => 'M 700 190 L 713 185 L 716 207 L 702 210 Z',
'LV' => 'M 522 100 L 535 98 L 536 105 L 523 106 Z',
'LB' => 'M 548 150 L 553 148 L 554 155 L 549 156 Z',
'LS' => 'M 522 295 L 528 293 L 529 300 L 523 301 Z',
'LR' => 'M 435 218 L 447 215 L 448 226 L 436 228 Z',
'LY' => 'M 498 155 L 535 150 L 537 178 L 500 182 Z',
'LT' => 'M 520 105 L 535 103 L 536 112 L 521 113 Z',
'MK' => 'M 516 135 L 524 133 L 525 140 L 517 141 Z',
'MG' => 'M 565 278 L 578 272 L 582 298 L 568 302 Z',
'MW' => 'M 535 260 L 541 257 L 543 273 L 536 275 Z',
'MY' => 'M 700 218 L 735 212 L 738 228 L 702 232 Z',
'ML' => 'M 440 185 L 475 180 L 478 210 L 442 215 Z',
'MR' => 'M 428 175 L 455 172 L 457 200 L 430 203 Z',
'MX' => 'M 115 155 L 200 148 L 210 190 L 195 205 L 150 200 L 115 180 Z',
'MD' => 'M 530 118 L 540 116 L 541 124 L 531 125 Z',
'MN' => 'M 652 115 L 730 108 L 733 140 L 655 145 Z',
'ME' => 'M 511 132 L 517 130 L 518 136 L 512 137 Z',
'MA' => 'M 440 148 L 460 145 L 462 168 L 441 171 Z',
'MZ' => 'M 533 265 L 552 260 L 555 295 L 535 298 Z',
'MM' => 'M 675 178 L 695 172 L 698 208 L 677 212 Z',
'NA' => 'M 495 275 L 520 270 L 522 295 L 497 298 Z',
'NP' => 'M 635 163 L 658 160 L 659 170 L 636 172 Z',
'NL' => 'M 483 107 L 494 105 L 495 114 L 484 115 Z',
'NZ' => 'M 845 365 L 855 358 L 858 378 L 848 382 Z',
'NI' => 'M 200 212 L 215 209 L 216 220 L 201 222 Z',
'NE' => 'M 462 183 L 500 178 L 502 208 L 464 212 Z',
'NG' => 'M 468 208 L 503 203 L 505 235 L 470 238 Z',
'NO' => 'M 490 72 L 520 62 L 535 85 L 510 92 L 490 88 Z',
'OM' => 'M 592 170 L 616 163 L 618 188 L 595 192 Z',
'PK' => 'M 606 150 L 640 145 L 643 175 L 620 182 L 607 172 Z',
'PS' => 'M 545 155 L 549 153 L 550 160 L 546 161 Z',
'PA' => 'M 213 222 L 228 218 L 229 228 L 214 230 Z',
'PG' => 'M 780 255 L 815 248 L 818 268 L 782 272 Z',
'PY' => 'M 265 310 L 285 305 L 288 328 L 267 331 Z',
'PE' => 'M 225 262 L 265 255 L 268 300 L 228 308 Z',
'PH' => 'M 745 195 L 773 188 L 776 220 L 748 224 Z',
'PL' => 'M 508 105 L 530 102 L 532 120 L 510 122 Z',
'PT' => 'M 450 125 L 462 122 L 463 140 L 451 143 Z',
'PR' => 'M 234 188 L 240 186 L 241 192 L 235 193 Z',
'RO' => 'M 520 118 L 540 115 L 542 130 L 522 132 Z',
'RU' => 'M 540 60 L 820 50 L 830 120 L 770 135 L 680 118 L 590 100 L 548 88 Z',
'RW' => 'M 530 245 L 537 242 L 538 250 L 531 251 Z',
'SA' => 'M 553 163 L 607 155 L 610 195 L 580 210 L 553 205 Z',
'SN' => 'M 425 198 L 448 195 L 450 208 L 427 211 Z',
'RS' => 'M 512 126 L 524 124 L 525 135 L 513 136 Z',
'SL' => 'M 430 218 L 442 215 L 443 225 L 431 227 Z',
'SO' => 'M 555 210 L 578 200 L 582 228 L 560 238 L 555 225 Z',
'ZA' => 'M 500 288 L 536 280 L 540 310 L 510 318 L 495 308 Z',
'SS' => 'M 525 215 L 547 210 L 549 232 L 527 235 Z',
'ES' => 'M 452 130 L 485 125 L 487 148 L 453 152 Z',
'LK' => 'M 641 205 L 647 202 L 649 213 L 643 215 Z',
'SD' => 'M 520 183 L 552 177 L 555 215 L 522 220 Z',
'SR' => 'M 268 228 L 280 225 L 281 238 L 269 240 Z',
'SZ' => 'M 526 292 L 532 290 L 533 297 L 527 298 Z',
'SE' => 'M 503 72 L 520 68 L 525 100 L 505 103 Z',
'CH' => 'M 487 118 L 502 116 L 503 124 L 488 125 Z',
'SY' => 'M 545 143 L 563 140 L 565 155 L 546 157 Z',
'TW' => 'M 753 172 L 759 169 L 761 178 L 755 180 Z',
'TJ' => 'M 625 135 L 642 132 L 644 142 L 627 144 Z',
'TZ' => 'M 530 250 L 555 244 L 557 272 L 532 275 Z',
'TH' => 'M 692 193 L 712 188 L 714 218 L 694 222 Z',
'TL' => 'M 762 258 L 775 255 L 776 263 L 763 265 Z',
'TG' => 'M 470 210 L 476 208 L 477 225 L 471 226 Z',
'TN' => 'M 490 143 L 502 141 L 503 158 L 491 160 Z',
'TR' => 'M 530 132 L 575 127 L 577 148 L 532 152 Z',
'TM' => 'M 590 130 L 623 126 L 625 145 L 592 148 Z',
'UG' => 'M 530 232 L 548 228 L 550 248 L 532 251 Z',
'UA' => 'M 522 108 L 560 104 L 562 128 L 524 132 Z',
'AE' => 'M 590 170 L 605 167 L 606 178 L 591 180 Z',
'GB' => 'M 460 100 L 480 95 L 482 118 L 462 122 Z',
'US' => 'M 55 105 L 215 98 L 225 148 L 215 178 L 150 185 L 60 168 Z',
'UY' => 'M 275 330 L 292 325 L 294 342 L 277 345 Z',
'UZ' => 'M 600 118 L 635 113 L 637 135 L 602 138 Z',
'VE' => 'M 235 220 L 270 212 L 273 240 L 237 245 Z',
'VN' => 'M 708 185 L 726 178 L 730 215 L 710 218 Z',
'YE' => 'M 563 188 L 608 180 L 610 202 L 565 207 Z',
'ZM' => 'M 515 258 L 543 252 L 545 278 L 517 281 Z',
'ZW' => 'M 518 275 L 540 270 L 542 292 L 520 294 Z',
];
// Compute top 10 for the ranked sidebar
$topCountries = collect($countryData)->sortDesc()->take(10);
// Country name lookup (ISO-2 → English name)
$countryNames = [
'AF'=>'Afghanistan','AL'=>'Albania','DZ'=>'Algeria','AO'=>'Angola','AR'=>'Argentina','AU'=>'Australia',
'AT'=>'Austria','AZ'=>'Azerbaijan','BD'=>'Bangladesh','BE'=>'Belgium','BF'=>'Burkina Faso','BY'=>'Belarus',
'BJ'=>'Benin','BO'=>'Bolivia','BA'=>'Bosnia & Herz.','BW'=>'Botswana','BR'=>'Brazil','BN'=>'Brunei',
'BG'=>'Bulgaria','KH'=>'Cambodia','CM'=>'Cameroon','CA'=>'Canada','CF'=>'C. African Rep.','TD'=>'Chad',
'CL'=>'Chile','CN'=>'China','CO'=>'Colombia','CD'=>'DR Congo','CG'=>'Congo','CR'=>'Costa Rica',
'HR'=>'Croatia','CU'=>'Cuba','CY'=>'Cyprus','CZ'=>'Czech Rep.','DK'=>'Denmark','DO'=>'Dominican Rep.',
'EC'=>'Ecuador','EG'=>'Egypt','SV'=>'El Salvador','GQ'=>'Eq. Guinea','ER'=>'Eritrea','EE'=>'Estonia',
'ET'=>'Ethiopia','FI'=>'Finland','FR'=>'France','GA'=>'Gabon','GM'=>'Gambia','GE'=>'Georgia',
'DE'=>'Germany','GH'=>'Ghana','GR'=>'Greece','GT'=>'Guatemala','GN'=>'Guinea','GW'=>'Guinea-Bissau',
'GY'=>'Guyana','HT'=>'Haiti','HN'=>'Honduras','HU'=>'Hungary','IN'=>'India','ID'=>'Indonesia',
'IR'=>'Iran','IQ'=>'Iraq','IE'=>'Ireland','IL'=>'Israel','IT'=>'Italy','CI'=>'Ivory Coast',
'JP'=>'Japan','JO'=>'Jordan','KZ'=>'Kazakhstan','KE'=>'Kenya','KP'=>'North Korea','KR'=>'South Korea',
'KW'=>'Kuwait','KG'=>'Kyrgyzstan','LA'=>'Laos','LV'=>'Latvia','LB'=>'Lebanon','LS'=>'Lesotho',
'LR'=>'Liberia','LY'=>'Libya','LT'=>'Lithuania','MK'=>'N. Macedonia','MG'=>'Madagascar','MW'=>'Malawi',
'MY'=>'Malaysia','ML'=>'Mali','MR'=>'Mauritania','MX'=>'Mexico','MD'=>'Moldova','MN'=>'Mongolia',
'ME'=>'Montenegro','MA'=>'Morocco','MZ'=>'Mozambique','MM'=>'Myanmar','NA'=>'Namibia','NP'=>'Nepal',
'NL'=>'Netherlands','NZ'=>'New Zealand','NI'=>'Nicaragua','NE'=>'Niger','NG'=>'Nigeria','NO'=>'Norway',
'OM'=>'Oman','PK'=>'Pakistan','PS'=>'Palestine','PA'=>'Panama','PG'=>'Papua N. Guinea','PY'=>'Paraguay',
'PE'=>'Peru','PH'=>'Philippines','PL'=>'Poland','PT'=>'Portugal','RO'=>'Romania','RU'=>'Russia',
'RW'=>'Rwanda','SA'=>'Saudi Arabia','SN'=>'Senegal','RS'=>'Serbia','SL'=>'Sierra Leone','SO'=>'Somalia',
'ZA'=>'South Africa','SS'=>'South Sudan','ES'=>'Spain','LK'=>'Sri Lanka','SD'=>'Sudan','SR'=>'Suriname',
'SZ'=>'Eswatini','SE'=>'Sweden','CH'=>'Switzerland','SY'=>'Syria','TW'=>'Taiwan','TJ'=>'Tajikistan',
'TZ'=>'Tanzania','TH'=>'Thailand','TG'=>'Togo','TN'=>'Tunisia','TR'=>'Turkey','TM'=>'Turkmenistan',
'UG'=>'Uganda','UA'=>'Ukraine','AE'=>'UAE','GB'=>'United Kingdom','US'=>'United States','UY'=>'Uruguay',
'UZ'=>'Uzbekistan','VE'=>'Venezuela','VN'=>'Vietnam','YE'=>'Yemen','ZM'=>'Zambia','ZW'=>'Zimbabwe',
];
// Unique Alpine.js component ID to allow multiple instances
$mapId = 'world-map-' . Str::random(8);
@endphp
<x-filament-widgets::widget>
<div class="rounded-2xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900/50">
{{-- Header --}}
<div class="mb-5 flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-indigo-50 text-indigo-500 dark:bg-indigo-950/50 dark:text-indigo-400">
<x-filament::icon icon="heroicon-o-globe-alt" class="h-5 w-5" />
</div>
<div>
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">
{{ __('filament-short-url::default.world_map_title') }}
</h3>
<p class="text-xs text-gray-500 dark:text-gray-400">
{{ number_format($totalClicks) }} {{ __('filament-short-url::default.world_map_total_clicks') }}
· {{ count($countryData) }} {{ __('filament-short-url::default.world_map_countries') }}
</p>
</div>
</div>
{{-- Legend --}}
<div class="hidden items-center gap-2 sm:flex">
<span class="text-xs text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.world_map_fewer') }}</span>
<div class="flex gap-0.5">
@foreach([10, 25, 45, 65, 85, 100] as $intensity)
<div class="h-4 w-4 rounded-sm" style="background: hsl(243 100% {{ max(30, 90 - $intensity * 0.55) }}% / {{ max(0.12, $intensity / 100) }});"></div>
@endforeach
</div>
<span class="text-xs text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.world_map_more') }}</span>
</div>
</div>
@if(empty($countryData))
{{-- Empty state --}}
<div class="flex flex-col items-center justify-center py-20 text-center">
<div class="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-gray-100 dark:bg-gray-800">
<x-filament::icon icon="heroicon-o-globe-alt" class="h-8 w-8 text-gray-400 dark:text-gray-500" />
</div>
<p class="text-sm font-medium text-gray-500 dark:text-gray-400">{{ __('filament-short-url::default.world_map_no_data') }}</p>
<p class="mt-1 text-xs text-gray-400 dark:text-gray-500">{{ __('filament-short-url::default.world_map_no_data_sub') }}</p>
</div>
@else
{{-- Map + Sidebar layout --}}
<div class="grid grid-cols-1 gap-6 lg:grid-cols-4">
{{-- SVG Map --}}
<div class="relative lg:col-span-3"
x-data="{
tooltip: { show: false, country: '', count: 0, x: 0, y: 0 },
showTooltip(country, count, event) {
this.tooltip = { show: true, country, count, x: event.offsetX, y: event.offsetY };
},
hideTooltip() { this.tooltip.show = false; }
}"
>
{{-- Tooltip --}}
<div x-show="tooltip.show"
x-cloak
:style="`left: ${tooltip.x + 12}px; top: ${tooltip.y - 8}px`"
class="pointer-events-none absolute z-20 rounded-lg border border-gray-200 bg-white px-3 py-2 shadow-xl dark:border-gray-700 dark:bg-gray-800"
style="min-width: 130px;"
>
<p class="text-xs font-semibold text-gray-800 dark:text-gray-200" x-text="tooltip.country"></p>
<p class="mt-0.5 text-xs text-indigo-600 dark:text-indigo-400">
<span x-text="tooltip.count.toLocaleString()"></span> clicks
</p>
</div>
<div class="overflow-hidden rounded-xl bg-gray-50 dark:bg-gray-800/50">
<svg viewBox="0 0 950 500" xmlns="http://www.w3.org/2000/svg"
class="h-full w-full"
style="min-height: 280px; max-height: 420px;"
>
{{-- Ocean background --}}
<rect width="950" height="500" fill="currentColor" class="text-gray-100 dark:text-gray-800" rx="8"/>
{{-- Grid lines (latitude/longitude) --}}
<g class="opacity-30" stroke="currentColor" stroke-width="0.5" class="text-gray-300 dark:text-gray-600">
@foreach([83, 167, 250, 333, 417] as $x)
<line x1="{{ $x }}" y1="0" x2="{{ $x }}" y2="500" stroke="#94a3b8" stroke-width="0.4" opacity="0.4"/>
@endforeach
@foreach([100, 200, 300, 400] as $y)
<line x1="0" y1="{{ $y }}" x2="950" y2="{{ $y }}" stroke="#94a3b8" stroke-width="0.4" opacity="0.4"/>
@endforeach
</g>
{{-- Countries --}}
@foreach($countryPaths as $code => $path)
@php
$count = $countryData[$code] ?? 0;
$intensity = $normalized[$code] ?? 0;
$name = $countryNames[$code] ?? $code;
if ($count > 0) {
// Active country: indigo hue, darkness based on intensity
$lightness = max(30, 88 - ($intensity * 0.55));
$alpha = max(0.15, $intensity / 100);
$fill = "hsl(243 100% {$lightness}% / {$alpha})";
$stroke = "hsl(243 80% 40% / 0.4)";
$strokeWidth = "0.8";
} else {
// Inactive country: neutral gray
$fill = "hsl(220 13% 91%)";
$stroke = "hsl(220 13% 80%)";
$strokeWidth = "0.4";
}
@endphp
<path
d="{{ $path }}"
fill="{{ $fill }}"
stroke="{{ $stroke }}"
stroke-width="{{ $strokeWidth }}"
class="{{ $count > 0 ? 'cursor-pointer transition-all duration-200 hover:brightness-90 hover:stroke-indigo-500' : '' }}"
@if($count > 0)
@mouseenter="showTooltip('{{ $name }}', {{ $count }}, $event)"
@mouseleave="hideTooltip()"
@endif
style="transition: fill 0.2s ease;"
/>
@endforeach
{{-- Pulse dots on top countries --}}
@php
$dotPositions = [
'US' => [135, 140], 'GB' => [471, 108], 'DE' => [502, 115], 'FR' => [480, 124],
'IN' => [638, 188], 'CN' => [692, 167], 'BR' => [287, 265], 'RU' => [685, 90],
'AU' => [775, 340], 'CA' => [127, 80], 'JP' => [782, 145], 'MX' => [162, 165],
'ES' => [468, 138], 'IT' => [504, 137], 'TR' => [553, 140], 'PL' => [520, 112],
'NL' => [488, 110], 'SA' => [580, 182], 'ZA' => [517, 299], 'AR' => [268, 360],
];
@endphp
@foreach($topCountries->take(5)->keys() as $rank => $code)
@if(isset($dotPositions[$code]))
@php [$dx, $dy] = $dotPositions[$code]; @endphp
<circle cx="{{ $dx }}" cy="{{ $dy }}" r="5" fill="hsl(243 100% 55%)" opacity="0.9">
<animate attributeName="r" values="5;9;5" dur="{{ 1.5 + $rank * 0.3 }}s" repeatCount="indefinite"/>
<animate attributeName="opacity" values="0.9;0.2;0.9" dur="{{ 1.5 + $rank * 0.3 }}s" repeatCount="indefinite"/>
</circle>
<circle cx="{{ $dx }}" cy="{{ $dy }}" r="3" fill="hsl(243 100% 65%)" opacity="1"/>
@endif
@endforeach
</svg>
</div>
</div>
{{-- Ranked Country Sidebar --}}
<div class="flex flex-col gap-1">
<p class="mb-2 text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">
{{ __('filament-short-url::default.world_map_top_countries') }}
</p>
@forelse($topCountries as $code => $count)
@php
$pct = $totalClicks > 0 ? round($count / $totalClicks * 100, 1) : 0;
$name = $countryNames[$code] ?? $code;
$barWidth = $maxCount > 0 ? round($count / $maxCount * 100) : 0;
@endphp
<div class="group rounded-lg px-2 py-1.5 transition-colors hover:bg-gray-50 dark:hover:bg-gray-800">
<div class="flex items-center gap-2">
<span class="w-5 text-center text-xs font-bold text-gray-400 dark:text-gray-500">
{{ $loop->iteration }}
</span>
<span class="flex-1 truncate text-sm font-medium text-gray-700 dark:text-gray-300">
{{ $name }}
</span>
<span class="shrink-0 font-mono text-xs font-semibold text-gray-900 dark:text-white">
{{ number_format($count) }}
</span>
<span class="w-9 shrink-0 text-right text-xs text-gray-400 dark:text-gray-500">
{{ $pct }}%
</span>
</div>
<div class="mt-1 ml-7 h-1 overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800">
<div class="h-full rounded-full bg-indigo-500 transition-all duration-700"
style="width: {{ $barWidth }}%">
</div>
</div>
</div>
@empty
<p class="py-4 text-center text-sm text-gray-400 dark:text-gray-500">
{{ __('filament-short-url::default.world_map_no_data') }}
</p>
@endforelse
</div>
</div>
@endif
</div>
</x-filament-widgets::widget>

View File

@@ -1,12 +1,23 @@
<?php
use Bjanczak\FilamentShortUrl\Http\Controllers\ShortUrlApiController;
use Bjanczak\FilamentShortUrl\Http\Controllers\ShortUrlRedirectController;
use Bjanczak\FilamentShortUrl\Http\Middleware\AuthenticateShortUrlApi;
use Illuminate\Support\Facades\Route;
Route::get(
Route::match(
['GET', 'POST'],
config('filament-short-url.route_prefix', 's').'/{key}',
ShortUrlRedirectController::class
)
->name('short-url.redirect')
->where('key', '[a-zA-Z0-9_-]+')
->middleware('throttle:120,1');
->middleware(config('filament-short-url.middleware', ['web', 'throttle:120,1']));
Route::prefix('api/short-url')
->middleware([AuthenticateShortUrlApi::class])
->group(function () {
Route::get('links', [ShortUrlApiController::class, 'index']);
Route::post('links', [ShortUrlApiController::class, 'store']);
Route::delete('links/{id}', [ShortUrlApiController::class, 'destroy']);
});

View File

@@ -0,0 +1,136 @@
<?php
namespace Bjanczak\FilamentShortUrl\Console\Commands;
use Bjanczak\FilamentShortUrl\Models\ShortUrlDailyStats;
use Bjanczak\FilamentShortUrl\Models\ShortUrlVisit;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class AggregateAndPruneVisitsCommand extends Command
{
/** @var string */
protected $signature = 'short-url:aggregate-and-prune';
/** @var string */
protected $description = 'Aggregate past days visits into daily stats and prune old raw visit logs';
public function handle(): int
{
$today = Carbon::today()->toDateString();
$driver = DB::connection()->getDriverName();
$dateExpression = match ($driver) {
'pgsql' => 'visited_at::date',
'sqlsrv' => 'CAST(visited_at AS DATE)',
default => 'DATE(visited_at)',
};
// 1. Find all unique dates before today that have visits (optimized range and compatible DATE extract)
$dates = ShortUrlVisit::where('visited_at', '<', $today)
->selectRaw("{$dateExpression} as visit_date")
->distinct()
->pluck('visit_date')
->toArray();
if (empty($dates)) {
$this->info('No historical visits to aggregate.');
} else {
$this->info('Found '.count($dates).' days to aggregate.');
foreach ($dates as $date) {
// Accumulate stats per short_url_id using chunked reads — avoids loading
// potentially millions of rows into PHP memory at once.
$statsByUrl = [];
$nextDate = Carbon::parse($date)->addDay()->toDateString();
ShortUrlVisit::where('visited_at', '>=', $date.' 00:00:00')
->where('visited_at', '<', $nextDate.' 00:00:00')
->chunk(1000, function ($chunk) use (&$statsByUrl): void {
foreach ($chunk as $visit) {
$urlId = $visit->short_url_id;
if (! isset($statsByUrl[$urlId])) {
$statsByUrl[$urlId] = [
'total' => 0,
'ip_hashes' => [],
'device_stats' => [],
'browser_stats' => [],
'os_stats' => [],
'country_stats' => [],
'city_stats' => [],
'referer_stats' => [],
'utm_source_stats' => [],
'utm_medium_stats' => [],
'utm_campaign_stats' => [],
];
}
$s = &$statsByUrl[$urlId];
$s['total']++;
if ($visit->ip_hash) {
$s['ip_hashes'][$visit->ip_hash] = true;
}
$inc = function (?string $value, string $key) use (&$s): void {
if ($value) {
$s[$key][$value] = ($s[$key][$value] ?? 0) + 1;
}
};
$inc($visit->device_type, 'device_stats');
$inc($visit->browser, 'browser_stats');
$inc($visit->operating_system, 'os_stats');
$inc($visit->country, 'country_stats');
$inc($visit->utm_source, 'utm_source_stats');
$inc($visit->utm_medium, 'utm_medium_stats');
$inc($visit->utm_campaign, 'utm_campaign_stats');
if ($visit->city) {
$cityKey = "{$visit->city} ({$visit->country_code})";
$s['city_stats'][$cityKey] = ($s['city_stats'][$cityKey] ?? 0) + 1;
}
if ($visit->referer_host) {
$s['referer_stats'][$visit->referer_host] = ($s['referer_stats'][$visit->referer_host] ?? 0) + 1;
}
}
});
foreach ($statsByUrl as $urlId => $s) {
ShortUrlDailyStats::updateOrCreate([
'short_url_id' => $urlId,
'date' => $date,
], [
'visits_count' => $s['total'],
'unique_visits_count' => count($s['ip_hashes']),
'device_stats' => $s['device_stats'],
'browser_stats' => $s['browser_stats'],
'os_stats' => $s['os_stats'],
'country_stats' => $s['country_stats'],
'city_stats' => $s['city_stats'],
'referer_stats' => $s['referer_stats'],
'utm_source_stats' => $s['utm_source_stats'],
'utm_medium_stats' => $s['utm_medium_stats'],
'utm_campaign_stats' => $s['utm_campaign_stats'],
]);
}
$this->info("Aggregated stats for {$date}.");
}
}
// 2. Prune old visits if enabled
if (config('filament-short-url.pruning.enabled', true)) {
$retentionDays = (int) config('filament-short-url.pruning.retention_days', 90);
$cutoff = Carbon::now()->subDays($retentionDays)->toDateTimeString();
$deleted = ShortUrlVisit::where('visited_at', '<', $cutoff)->delete();
$this->info("Successfully pruned {$deleted} raw visit records older than {$retentionDays} days.");
}
return 0;
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Bjanczak\FilamentShortUrl\Console\Commands;
use Bjanczak\FilamentShortUrl\Models\ShortUrl;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class SyncBufferedCountersCommand extends Command
{
/** @var string */
protected $signature = 'short-url:sync-counters';
/** @var string */
protected $description = 'Sync buffered short URL visit counters from cache to the database';
public function handle(): int
{
$prefix = config('filament-short-url.counter_buffering.cache_key_prefix', 'filament-short-url:buffer:');
$dirtyKey = "{$prefix}dirty_ids";
// Pull the list atomically to avoid race conditions with incoming clicks
if (Cache::getDefaultDriver() === 'redis' && class_exists(Redis::class)) {
$tempKey = "{$dirtyKey}:temp:".time();
try {
Redis::rename($dirtyKey, $tempKey);
$dirtyIds = Redis::smembers($tempKey);
Redis::del($tempKey);
} catch (\Throwable) {
// If key does not exist or rename fails, fallback
$dirtyIds = [];
}
} else {
$dirtyIds = Cache::pull($dirtyKey, []);
}
if (empty($dirtyIds)) {
$this->info('No buffered counters to synchronize.');
return 0;
}
$dirtyIds = array_unique(array_filter($dirtyIds));
$processed = 0;
foreach ($dirtyIds as $id) {
$totalKey = "{$prefix}total:{$id}";
$uniqueKey = "{$prefix}unique:{$id}";
$totalDelta = (int) Cache::pull($totalKey, 0);
$uniqueDelta = (int) Cache::pull($uniqueKey, 0);
if ($totalDelta > 0 || $uniqueDelta > 0) {
// Perform a single atomic update query for this URL
ShortUrl::where('id', $id)->update([
'total_visits' => DB::raw("total_visits + {$totalDelta}"),
'unique_visits' => DB::raw("unique_visits + {$uniqueDelta}"),
]);
$processed++;
}
}
$this->info("Successfully synchronized counters for {$processed} short URLs.");
return 0;
}
}

View File

@@ -26,6 +26,15 @@ class ShortUrlResource extends Resource
public static function getNavigationLabel(): string
{
try {
$label = FilamentShortUrlPlugin::get()->getNavigationLabel();
if ($label) {
return $label;
}
} catch (\Throwable) {
// Ignore
}
return __('filament-short-url::default.navigation_label');
}
@@ -41,6 +50,20 @@ class ShortUrlResource extends Resource
// ─── Plugin-aware navigation overrides ───────────────────────────────────
public static function getNavigationIcon(): string|\BackedEnum|null
{
try {
$icon = FilamentShortUrlPlugin::get()->getNavigationIcon();
if ($icon) {
return $icon;
}
} catch (\Throwable) {
// Ignore
}
return static::$navigationIcon;
}
public static function getNavigationGroup(): string|\UnitEnum|null
{
try {

View File

@@ -3,6 +3,7 @@
namespace Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Pages;
use Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource;
use Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlGlobalOverview;
use Bjanczak\FilamentShortUrl\Services\ShortUrlService;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
@@ -40,6 +41,8 @@ class ListShortUrls extends ManageRecords
protected function getHeaderWidgets(): array
{
return [];
return [
ShortUrlGlobalOverview::class,
];
}
}

View File

@@ -3,8 +3,11 @@
namespace Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Pages;
use Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource;
use Bjanczak\FilamentShortUrl\Services\SafeBrowsingService;
use Bjanczak\FilamentShortUrl\Services\ShortUrlSettingsManager;
use Filament\Actions\Action;
use Filament\Forms\Components\ColorPicker;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
@@ -12,11 +15,13 @@ use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Illuminate\Support\Facades\Http;
class ShortUrlSettingsPage extends Page implements HasForms
{
@@ -41,10 +46,48 @@ class ShortUrlSettingsPage extends Page implements HasForms
'geo_ip_driver' => $mgr->get('geo_ip_driver', 'headers'),
'geo_ip_cache_ttl' => $mgr->get('geo_ip_cache_ttl', 86400),
'geo_ip_timeout' => $mgr->get('geo_ip_timeout', 3),
'maxmind_database_path' => $mgr->get('maxmind_database_path', database_path('geoip/GeoLite2-Country.mmdb')),
'maxmind_database_path' => $mgr->get('maxmind_database_path', storage_path('geoip/GeoLite2-Country.mmdb')),
'geo_ip_stats_cache_ttl' => $mgr->get('geo_ip_stats_cache_ttl', 300),
'queue_connection' => $mgr->get('queue_connection', 'sync'),
'queue_name' => $mgr->get('queue_name', 'default'),
'ga4_api_secret' => $mgr->get('ga4_api_secret'),
'ga4_firebase_app_id' => $mgr->get('ga4_firebase_app_id'),
'counter_buffering_enabled' => $mgr->get('counter_buffering_enabled', false),
'trust_cdn_headers' => $mgr->get('trust_cdn_headers', false),
'pruning_enabled' => $mgr->get('pruning_enabled', true),
'pruning_retention_days' => $mgr->get('pruning_retention_days', 90),
'rate_limiting_enabled' => $mgr->get('rate_limiting_enabled', false),
'rate_limiting_max_attempts' => $mgr->get('rate_limiting_max_attempts', 60),
'rate_limiting_decay_seconds' => $mgr->get('rate_limiting_decay_seconds', 60),
'tracking_enabled' => $mgr->get('tracking_enabled', true),
'tracking_fields_ip_address' => $mgr->get('tracking_fields_ip_address', true),
'tracking_fields_browser' => $mgr->get('tracking_fields_browser', true),
'tracking_fields_browser_version' => $mgr->get('tracking_fields_browser_version', true),
'tracking_fields_operating_system' => $mgr->get('tracking_fields_operating_system', true),
'tracking_fields_operating_system_version' => $mgr->get('tracking_fields_operating_system_version', true),
'tracking_fields_referer_url' => $mgr->get('tracking_fields_referer_url', true),
'tracking_fields_device_type' => $mgr->get('tracking_fields_device_type', true),
'qr_size' => $mgr->get('qr_size', 300),
'qr_margin' => $mgr->get('qr_margin', 1),
'qr_dot_style' => $mgr->get('qr_dot_style', 'square'),
'qr_foreground_color' => $mgr->get('qr_foreground_color', '#000000'),
'qr_background_color' => $mgr->get('qr_background_color', '#ffffff'),
'qr_gradient_enabled' => $mgr->get('qr_gradient_enabled', false),
'qr_gradient_from' => $mgr->get('qr_gradient_from', '#4f46e5'),
'qr_gradient_to' => $mgr->get('qr_gradient_to', '#06b6d4'),
'qr_gradient_type' => $mgr->get('qr_gradient_type', 'linear'),
'global_webhook_url' => $mgr->get('global_webhook_url'),
'webhook_events' => $mgr->get('webhook_events', ['visited']),
'api_keys' => $mgr->get('api_keys', []),
'api_enabled' => $mgr->get('api_enabled', false),
'site_name' => $mgr->get('site_name'),
// Security v2.0
'vpn_detection_enabled' => $mgr->get('vpn_detection_enabled', false),
'vpn_detection_driver' => $mgr->get('vpn_detection_driver', 'ip-api'),
'vpnapi_key' => $mgr->get('vpnapi_key'),
'vpn_block_action' => $mgr->get('vpn_block_action', 'flag_only'),
'safe_browsing_enabled' => $mgr->get('safe_browsing_enabled', false),
'google_safe_browsing_api_key' => $mgr->get('google_safe_browsing_api_key'),
]);
}
@@ -63,6 +106,13 @@ class ShortUrlSettingsPage extends Page implements HasForms
Section::make(__('filament-short-url::default.settings_section_routing'))
->columns(2)
->schema([
TextInput::make('site_name')
->label(__('filament-short-url::default.settings_site_name'))
->helperText(__('filament-short-url::default.settings_site_name_helper'))
->nullable()
->maxLength(100)
->columnSpanFull(),
TextInput::make('route_prefix')
->label(__('filament-short-url::default.settings_route_prefix'))
->helperText(__('filament-short-url::default.settings_route_prefix_helper'))
@@ -82,6 +132,7 @@ class ShortUrlSettingsPage extends Page implements HasForms
->label(__('filament-short-url::default.settings_key_length'))
->helperText(__('filament-short-url::default.settings_key_length_helper'))
->numeric()
->integer()
->minValue(4)
->maxValue(20)
->required(),
@@ -90,12 +141,20 @@ class ShortUrlSettingsPage extends Page implements HasForms
->label(__('filament-short-url::default.settings_cache_ttl'))
->helperText(__('filament-short-url::default.settings_cache_ttl_helper'))
->numeric()
->integer()
->minValue(0)
->suffix('s')
->required(),
Toggle::make('trust_cdn_headers')
->label(__('filament-short-url::default.settings_trust_cdn_headers'))
->helperText(__('filament-short-url::default.settings_trust_cdn_headers_helper'))
->columnSpanFull()
->inline(false),
]),
Section::make(__('filament-short-url::default.settings_section_queue'))
->columns(2)
->schema([
Select::make('queue_connection')
->label(__('filament-short-url::default.settings_queue_connection'))
@@ -110,6 +169,19 @@ class ShortUrlSettingsPage extends Page implements HasForms
];
})
->required(),
TextInput::make('queue_name')
->label(__('filament-short-url::default.settings_queue_name'))
->helperText(__('filament-short-url::default.settings_queue_name_helper'))
->required(),
]),
Section::make(__('filament-short-url::default.settings_section_buffering'))
->schema([
Toggle::make('counter_buffering_enabled')
->label(__('filament-short-url::default.settings_buffering_enabled'))
->helperText(__('filament-short-url::default.settings_buffering_helper'))
->inline(false),
]),
]),
@@ -145,6 +217,18 @@ class ShortUrlSettingsPage extends Page implements HasForms
->label(__('filament-short-url::default.settings_geoip_cache_ttl'))
->helperText(__('filament-short-url::default.settings_geoip_cache_ttl_helper'))
->numeric()
->integer()
->minValue(0)
->suffix('s')
->required()
->visible(fn (Get $get): bool => (bool) $get('geo_ip_enabled')),
// ── Stats Cache TTL (only when geo-ip is on) ──
TextInput::make('geo_ip_stats_cache_ttl')
->label(__('filament-short-url::default.settings_geoip_stats_cache_ttl'))
->helperText(__('filament-short-url::default.settings_geoip_stats_cache_ttl_helper'))
->numeric()
->integer()
->minValue(0)
->suffix('s')
->required()
@@ -155,6 +239,7 @@ class ShortUrlSettingsPage extends Page implements HasForms
->label(__('filament-short-url::default.settings_geoip_timeout'))
->helperText(__('filament-short-url::default.settings_geoip_timeout_helper'))
->numeric()
->integer()
->minValue(1)
->maxValue(30)
->suffix('s')
@@ -166,7 +251,39 @@ class ShortUrlSettingsPage extends Page implements HasForms
->label(__('filament-short-url::default.settings_maxmind_path'))
->helperText(__('filament-short-url::default.settings_maxmind_path_helper'))
->columnSpanFull()
->placeholder(database_path('geoip/GeoLite2-Country.mmdb'))
->placeholder('/var/www/html/database/geoip/GeoLite2-Country.mmdb')
->suffixAction(
Action::make('verifyMaxmindPath')
->label(__('filament-short-url::default.settings_maxmind_verify'))
->icon('heroicon-o-server')
->action(function (?string $state): void {
$path = trim($state ?? '');
if (empty($path)) {
Notification::make()
->title(__('filament-short-url::default.settings_maxmind_verify_empty'))
->warning()
->send();
return;
}
if (file_exists($path) && is_readable($path) && str_ends_with($path, '.mmdb')) {
$sizeKb = round(filesize($path) / 1024);
Notification::make()
->title(__('filament-short-url::default.settings_maxmind_verify_ok'))
->body("{$path} ({$sizeKb} KB)")
->success()
->send();
} else {
Notification::make()
->title(__('filament-short-url::default.settings_maxmind_verify_fail'))
->body($path)
->danger()
->send();
}
})
)
->visible(fn (Get $get): bool => (bool) $get('geo_ip_enabled') && $get('geo_ip_driver') === 'maxmind'),
]),
]),
@@ -183,15 +300,416 @@ class ShortUrlSettingsPage extends Page implements HasForms
->helperText(__('filament-short-url::default.settings_ga4_api_secret_helper'))
->password()
->revealable()
->live()
->placeholder('••••••••••••••••••••'),
// Firebase App ID only when API Secret is set
// Firebase App ID — always visible
TextInput::make('ga4_firebase_app_id')
->label(__('filament-short-url::default.settings_ga4_firebase_app_id'))
->helperText(__('filament-short-url::default.settings_ga4_firebase_app_id_helper'))
->placeholder('1:1234567890:android:abcdef123456')
->visible(fn (Get $get): bool => filled($get('ga4_api_secret'))),
->placeholder('1:1234567890:android:abcdef123456'),
// GA4 connection verify button
Actions::make([
Action::make('verifyGa4ApiSecret')
->label(__('filament-short-url::default.settings_ga4_verify'))
->icon('heroicon-o-signal')
->color('gray')
->action(function (Get $get): void {
$secret = trim($get('ga4_api_secret') ?? '');
if (empty($secret)) {
Notification::make()
->title(__('filament-short-url::default.settings_ga4_verify_empty'))
->warning()
->send();
return;
}
try {
// GA4 debug endpoint — a valid api_secret returns event-level
// validation messages; an invalid one returns auth errors.
$response = Http::timeout(5)
->withHeaders(['Content-Type' => 'application/json'])
->post(
'https://www.google-analytics.com/debug/mp/collect?measurement_id=G-XXXXXXXXXX&api_secret='.urlencode($secret),
[
'client_id' => 'short-url-plugin-verify',
'events' => [
['name' => 'page_view', 'params' => []],
],
]
);
$body = $response->json();
$messages = $body['validationMessages'] ?? [];
// A valid secret returns event-level messages, not auth errors
$hasAuthError = collect($messages)->contains(fn ($m) => str_contains(
strtolower($m['description'] ?? ''),
'api_secret'
));
if ($hasAuthError || $response->status() === 401) {
Notification::make()
->title(__('filament-short-url::default.settings_ga4_verify_fail'))
->danger()
->send();
} else {
Notification::make()
->title(__('filament-short-url::default.settings_ga4_verify_ok'))
->success()
->send();
}
} catch (\Throwable $e) {
Notification::make()
->title(__('filament-short-url::default.settings_ga4_verify_error'))
->body($e->getMessage())
->danger()
->send();
}
}),
]),
]),
]),
// ── Advanced & Security ──────────────────────────────
Tab::make(__('filament-short-url::default.settings_tab_advanced'))
->icon('heroicon-o-adjustments-horizontal')
->schema([
Section::make(__('filament-short-url::default.settings_section_aggregation'))
->columns(2)
->schema([
Toggle::make('pruning_enabled')
->label(__('filament-short-url::default.settings_aggregation_enabled'))
->helperText(__('filament-short-url::default.settings_aggregation_enabled_helper'))
->default(true)
->live()
->inline(false),
Select::make('pruning_retention_days')
->label(__('filament-short-url::default.settings_retention_days'))
->helperText(__('filament-short-url::default.settings_retention_days_helper'))
->options([
30 => __('filament-short-url::default.retention_30_days'),
60 => __('filament-short-url::default.retention_60_days'),
90 => __('filament-short-url::default.retention_90_days'),
180 => __('filament-short-url::default.retention_180_days'),
365 => __('filament-short-url::default.retention_365_days'),
730 => __('filament-short-url::default.retention_730_days'),
])
->required()
->visible(fn (Get $get): bool => (bool) $get('pruning_enabled')),
]),
Section::make(__('filament-short-url::default.settings_section_rate_limiting'))
->columns(3)
->schema([
Toggle::make('rate_limiting_enabled')
->label(__('filament-short-url::default.settings_rate_limiting_enabled'))
->helperText(__('filament-short-url::default.settings_rate_limiting_enabled_helper'))
->default(false)
->live()
->inline(false),
TextInput::make('rate_limiting_max_attempts')
->label(__('filament-short-url::default.settings_rate_limiting_max_attempts'))
->helperText(__('filament-short-url::default.settings_rate_limiting_max_attempts_helper'))
->numeric()
->integer()
->minValue(1)
->required()
->visible(fn (Get $get): bool => (bool) $get('rate_limiting_enabled')),
TextInput::make('rate_limiting_decay_seconds')
->label(__('filament-short-url::default.settings_rate_limiting_decay_seconds'))
->helperText(__('filament-short-url::default.settings_rate_limiting_decay_seconds_helper'))
->numeric()
->integer()
->minValue(1)
->suffix('s')
->required()
->visible(fn (Get $get): bool => (bool) $get('rate_limiting_enabled')),
]),
Section::make(__('filament-short-url::default.settings_section_security_v2'))
->description(__('filament-short-url::default.settings_section_security_v2_desc'))
->columns(2)
->schema([
Toggle::make('vpn_detection_enabled')
->label(__('filament-short-url::default.settings_vpn_detection_enabled'))
->helperText(__('filament-short-url::default.settings_vpn_detection_enabled_helper'))
->default(false)
->inline(false)
->live()
->columnSpanFull(),
Select::make('vpn_detection_driver')
->label(__('filament-short-url::default.settings_vpn_driver'))
->helperText(__('filament-short-url::default.settings_vpn_driver_helper'))
->options([
'ip-api' => __('filament-short-url::default.settings_vpn_driver_ipapi'),
'vpnapi' => __('filament-short-url::default.settings_vpn_driver_vpnapi'),
])
->default('ip-api')
->live()
->required()
->visible(fn (Get $get): bool => (bool) $get('vpn_detection_enabled')),
TextInput::make('vpnapi_key')
->label(__('filament-short-url::default.settings_vpnapi_key'))
->helperText(__('filament-short-url::default.settings_vpnapi_key_helper'))
->password()
->revealable()
->placeholder('••••••••••••••••••••')
->visible(fn (Get $get): bool => (bool) $get('vpn_detection_enabled') && $get('vpn_detection_driver') === 'vpnapi'),
Select::make('vpn_block_action')
->label(__('filament-short-url::default.settings_vpn_block_action'))
->helperText(__('filament-short-url::default.settings_vpn_block_action_helper'))
->options([
'flag_only' => __('filament-short-url::default.settings_vpn_block_flag_only'),
'block_with_403' => __('filament-short-url::default.settings_vpn_block_block_403'),
])
->default('flag_only')
->required()
->visible(fn (Get $get): bool => (bool) $get('vpn_detection_enabled')),
Toggle::make('safe_browsing_enabled')
->label(__('filament-short-url::default.settings_safe_browsing_enabled'))
->helperText(__('filament-short-url::default.settings_safe_browsing_enabled_helper'))
->default(false)
->inline(false)
->live()
->columnSpanFull(),
TextInput::make('google_safe_browsing_api_key')
->label(__('filament-short-url::default.settings_safe_browsing_api_key'))
->helperText(__('filament-short-url::default.settings_safe_browsing_api_key_helper'))
->password()
->revealable()
->placeholder('AIza••••••••••••••••••')
->columnSpanFull()
->suffixAction(
Action::make('testSafeBrowsing')
->label(__('filament-short-url::default.settings_safe_browsing_test'))
->icon('heroicon-o-signal')
->color('gray')
->action(function (Get $get): void {
$key = trim($get('google_safe_browsing_api_key') ?? '');
if (empty($key)) {
Notification::make()
->title(__('filament-short-url::default.settings_safe_browsing_test_empty'))
->warning()->send();
return;
}
try {
$svc = app(SafeBrowsingService::class);
$safe = $svc->isSafeWithKey('https://google.com', $key);
Notification::make()
->title($safe
? __('filament-short-url::default.settings_safe_browsing_test_ok')
: __('filament-short-url::default.settings_safe_browsing_test_fail'))
->color($safe ? 'success' : 'danger')
->send();
} catch (\Throwable $e) {
Notification::make()
->title(__('filament-short-url::default.settings_safe_browsing_test_error'))
->body($e->getMessage())
->danger()->send();
}
})
)
->visible(fn (Get $get): bool => (bool) $get('safe_browsing_enabled')),
]),
]),
// ── Tracking Defaults ─────────────────────────────────
Tab::make(__('filament-short-url::default.settings_tab_tracking_defaults'))
->icon('heroicon-o-chart-bar')
->schema([
Section::make(__('filament-short-url::default.settings_section_tracking_defaults'))
->description(__('filament-short-url::default.settings_section_tracking_defaults_helper'))
->schema([
Toggle::make('tracking_enabled')
->label(__('filament-short-url::default.settings_track_visits_default'))
->live()
->inline(false)
->columnSpanFull(),
Toggle::make('tracking_fields_ip_address')
->label(__('filament-short-url::default.settings_track_ip_default'))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('tracking_enabled')),
Toggle::make('tracking_fields_browser')
->label(__('filament-short-url::default.settings_track_browser_default'))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('tracking_enabled')),
Toggle::make('tracking_fields_browser_version')
->label(__('filament-short-url::default.settings_track_browser_version_default'))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('tracking_enabled')),
Toggle::make('tracking_fields_operating_system')
->label(__('filament-short-url::default.settings_track_os_default'))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('tracking_enabled')),
Toggle::make('tracking_fields_operating_system_version')
->label(__('filament-short-url::default.settings_track_os_version_default'))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('tracking_enabled')),
Toggle::make('tracking_fields_referer_url')
->label(__('filament-short-url::default.settings_track_referer_default'))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('tracking_enabled')),
Toggle::make('tracking_fields_device_type')
->label(__('filament-short-url::default.settings_track_device_type_default'))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('tracking_enabled')),
])
->columns(4),
]),
// ── QR Defaults ──────────────────────────────────────
Tab::make(__('filament-short-url::default.settings_tab_qr'))
->icon('heroicon-o-qr-code')
->schema([
Section::make(__('filament-short-url::default.settings_section_qr_defaults'))
->description(__('filament-short-url::default.settings_section_qr_defaults_helper'))
->columns(2)
->schema([
TextInput::make('qr_size')
->label(__('filament-short-url::default.settings_qr_size'))
->numeric()
->integer()
->minValue(100)
->maxValue(2000)
->required(),
Select::make('qr_margin')
->label(__('filament-short-url::default.settings_qr_margin'))
->options(array_combine(range(0, 10), range(0, 10)))
->required(),
Select::make('qr_dot_style')
->label(__('filament-short-url::default.settings_qr_dot_style'))
->options([
'square' => __('filament-short-url::default.qr_option_square'),
'dots' => __('filament-short-url::default.qr_option_dots'),
'rounded' => __('filament-short-url::default.qr_option_rounded'),
'classy' => __('filament-short-url::default.qr_option_classy'),
'classy-rounded' => __('filament-short-url::default.qr_option_classy_rounded'),
'extra-rounded' => __('filament-short-url::default.qr_option_extra_rounded'),
])
->required(),
ColorPicker::make('qr_foreground_color')
->label(__('filament-short-url::default.settings_qr_foreground_color'))
->regex('/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})\b$/')
->placeholder('#000000')
->required(),
ColorPicker::make('qr_background_color')
->label(__('filament-short-url::default.settings_qr_background_color'))
->regex('/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})\b$/')
->placeholder('#ffffff')
->required(),
Toggle::make('qr_gradient_enabled')
->label(__('filament-short-url::default.settings_qr_gradient_enabled'))
->live()
->inline(false),
ColorPicker::make('qr_gradient_from')
->label(__('filament-short-url::default.settings_qr_gradient_from'))
->regex('/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})\b$/')
->placeholder('#4f46e5')
->required(fn (Get $get): bool => (bool) $get('qr_gradient_enabled'))
->visible(fn (Get $get): bool => (bool) $get('qr_gradient_enabled')),
ColorPicker::make('qr_gradient_to')
->label(__('filament-short-url::default.settings_qr_gradient_to'))
->regex('/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})\b$/')
->placeholder('#06b6d4')
->required(fn (Get $get): bool => (bool) $get('qr_gradient_enabled'))
->visible(fn (Get $get): bool => (bool) $get('qr_gradient_enabled')),
Select::make('qr_gradient_type')
->label(__('filament-short-url::default.settings_qr_gradient_type'))
->options([
'linear' => __('filament-short-url::default.qr_gradient_linear'),
'radial' => __('filament-short-url::default.qr_gradient_radial'),
])
->required(fn (Get $get): bool => (bool) $get('qr_gradient_enabled'))
->visible(fn (Get $get): bool => (bool) $get('qr_gradient_enabled')),
]),
]),
// ── Developer API & Webhooks ────────────────────────
Tab::make(__('filament-short-url::default.settings_tab_developer'))
->icon('heroicon-o-cpu-chip')
->schema([
Section::make(__('filament-short-url::default.settings_section_rest_api'))
->schema([
Toggle::make('api_enabled')
->label(__('filament-short-url::default.settings_api_enabled'))
->helperText(__('filament-short-url::default.settings_api_enabled_helper'))
->default(false)
->inline(false)
->columnSpanFull()
->live(),
]),
Section::make(__('filament-short-url::default.settings_section_api_keys'))
->description(__('filament-short-url::default.settings_api_keys_description'))
->visible(fn (Get $get): bool => (bool) $get('api_enabled'))
->schema([
Repeater::make('api_keys')
->label(__('filament-short-url::default.settings_api_keys'))
->schema([
TextInput::make('name')
->label(__('filament-short-url::default.api_key_name'))
->required(),
TextInput::make('key')
->label(__('filament-short-url::default.api_key'))
->disabled()
->dehydrated()
->default(fn () => 'sh_key_'.bin2hex(random_bytes(16))),
Toggle::make('is_active')
->label(__('filament-short-url::default.active'))
->default(true),
])
->columns(3)
->default([]),
]),
Section::make(__('filament-short-url::default.settings_section_global_webhook'))
->schema([
TextInput::make('global_webhook_url')
->label(__('filament-short-url::default.settings_global_webhook_url'))
->helperText(__('filament-short-url::default.settings_global_webhook_url_helper'))
->url()
->nullable()
->columnSpanFull(),
Select::make('webhook_events')
->label(__('filament-short-url::default.settings_webhook_events'))
->helperText(__('filament-short-url::default.settings_webhook_events_helper'))
->multiple()
->options([
'visited' => __('filament-short-url::default.webhook_event_visited'),
'created' => __('filament-short-url::default.webhook_event_created'),
'expired' => __('filament-short-url::default.webhook_event_expired'),
'limit_reached' => __('filament-short-url::default.webhook_event_limit_reached'),
])
->default(['visited'])
->columnSpanFull(),
]),
]),
]),

View File

@@ -112,31 +112,38 @@ class ViewShortUrlLogs extends Page implements HasForms, HasTable
Tables\Filters\Filter::make('visited_at')
->form([
DatePicker::make('visited_from')
->label('Visited From'),
->label(__('filament-short-url::default.stats_filter_visited_from')),
DatePicker::make('visited_until')
->label('Visited Until'),
->label(__('filament-short-url::default.stats_filter_visited_until')),
])
->query(function ($query, array $data) {
return $query
->when($data['visited_from'], fn ($q, $date) => $q->whereDate('visited_at', '>=', $date))
->when($data['visited_until'], fn ($q, $date) => $q->whereDate('visited_at', '<=', $date));
->when($data['visited_from'], fn ($q, $date) => $q->where('visited_at', '>=', $date.' 00:00:00'))
->when($data['visited_until'], fn ($q, $date) => $q->where('visited_at', '<=', $date.' 23:59:59'));
}),
])
->headerActions([
Action::make('export_csv')
->label('Export CSV')
->label(__('filament-short-url::default.stats_action_export'))
->icon('heroicon-o-arrow-down-tray')
->color('gray')
->action(function () {
return response()->streamDownload(function () {
->action(function (HasTable $livewire) {
return response()->streamDownload(function () use ($livewire) {
$handle = fopen('php://output', 'w');
// Add UTF-8 BOM for Microsoft Excel
fprintf($handle, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($handle, ['Time', 'IP Address', 'Country', 'Device', 'Browser', 'OS', 'Referer']);
fputcsv($handle, [
__('filament-short-url::default.stats_csv_time'),
__('filament-short-url::default.stats_csv_ip'),
__('filament-short-url::default.stats_csv_country'),
__('filament-short-url::default.stats_csv_device'),
__('filament-short-url::default.stats_csv_browser'),
__('filament-short-url::default.stats_csv_os'),
__('filament-short-url::default.stats_csv_referer'),
]);
ShortUrlVisit::query()
->where('short_url_id', $this->record->id)
$livewire->getFilteredTableQuery()
->orderBy('visited_at', 'desc')
->chunk(200, function ($visits) use ($handle) {
foreach ($visits as $visit) {

View File

@@ -5,9 +5,12 @@ namespace Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Pages;
use Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource;
use Bjanczak\FilamentShortUrl\Models\ShortUrl;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Resources\Pages\Page;
use Filament\Schemas\Schema;
class ViewShortUrlStats extends Page implements HasForms
{
@@ -23,10 +26,80 @@ class ViewShortUrlStats extends Page implements HasForms
public int $totalVisits = 0;
public ?array $filterData = [];
public function mount(ShortUrl $record): void
{
$this->record = $record;
$this->totalVisits = $record->getCachedStats()['totalVisits'] ?? 0;
$this->form->fill([
'preset' => '30_days',
'date_from' => now()->subDays(29)->format('Y-m-d'),
'date_to' => now()->format('Y-m-d'),
]);
if (empty($this->filterData)) {
$this->filterData = [
'preset' => '30_days',
'date_from' => now()->subDays(29)->format('Y-m-d'),
'date_to' => now()->format('Y-m-d'),
];
}
$this->totalVisits = $record->getCachedStats($this->filterData['date_from'], $this->filterData['date_to'])['totalVisits'] ?? 0;
}
public function form(Schema $schema): Schema
{
return $schema
->components([
Select::make('preset')
->hiddenLabel()
->options([
'24_hours' => __('filament-short-url::default.stats_preset_24_hours'),
'7_days' => __('filament-short-url::default.stats_preset_7_days'),
'30_days' => __('filament-short-url::default.stats_preset_30_days'),
'90_days' => __('filament-short-url::default.stats_preset_90_days'),
'custom' => __('filament-short-url::default.stats_preset_custom'),
])
->live()
->columnSpan(fn ($get) => $get('preset') === 'custom' ? 1 : 'full')
->afterStateUpdated(function ($state, $set) {
$to = now()->format('Y-m-d');
$from = match ($state) {
'24_hours' => now()->subDay()->format('Y-m-d'),
'7_days' => now()->subDays(6)->format('Y-m-d'),
'30_days' => now()->subDays(29)->format('Y-m-d'),
'90_days' => now()->subDays(89)->format('Y-m-d'),
'custom' => now()->subDays(29)->format('Y-m-d'),
default => null,
};
if ($from) {
$set('date_from', $from);
$set('date_to', $to);
}
}),
DatePicker::make('date_from')
->hiddenLabel()
->placeholder(__('filament-short-url::default.stats_filter_visited_from'))
->native(false)
->live()
->columnSpan(1)
->visible(fn ($get) => $get('preset') === 'custom')
->required(),
DatePicker::make('date_to')
->hiddenLabel()
->placeholder(__('filament-short-url::default.stats_filter_visited_until'))
->native(false)
->live()
->columnSpan(1)
->visible(fn ($get) => $get('preset') === 'custom')
->required(),
])
->columns(3)
->statePath('filterData');
}
protected function getHeaderWidgets(): array

View File

@@ -5,6 +5,7 @@ namespace Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Schemas;
use Bjanczak\FilamentShortUrl\Services\ShortUrlService;
use Filament\Actions\Action;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
@@ -24,7 +25,9 @@ class ShortUrlForm
return $schema->components([
Tabs::make()->tabs([
static::linkTab(),
static::targetingTab(),
static::trackingTab(),
static::marketingTab(),
static::qrDesignTab(),
])->columnSpanFull(),
]);
@@ -42,6 +45,14 @@ class ShortUrlForm
->required()
->url()
->maxLength(2048)
->rules([
fn (): \Closure => function (string $attribute, $value, \Closure $fail) {
$safeBrowsing = app(\Bjanczak\FilamentShortUrl\Services\SafeBrowsingService::class);
if (! $safeBrowsing->isSafe($value)) {
$fail(__('filament-short-url::default.safe_browsing_error') ?? 'This URL has been flagged by Google Safe Browsing as unsafe.');
}
},
])
->live(onBlur: true)
->afterStateHydrated(function (TextInput $component, $state, Set $set) {
if (! $state) {
@@ -101,35 +112,90 @@ class ShortUrlForm
302 => __('filament-short-url::default.redirect_code_302'),
301 => __('filament-short-url::default.redirect_code_301'),
])
->default(302)
->default(fn () => config('filament-short-url.redirect_status_code', 302))
->required(),
])->columns(2),
Section::make('Options')->schema([
Section::make(__('filament-short-url::default.form_section_options'))->schema([
Toggle::make('is_enabled')
->label(__('filament-short-url::default.status'))
->default(true)
->inline(false),
Toggle::make('single_use')
->label(__('filament-short-url::default.single_use'))
->helperText(__('filament-short-url::default.single_use_helper'))
->default(false)
->inline(false),
Toggle::make('forward_query_params')
->label(__('filament-short-url::default.forward_query_params'))
->helperText(__('filament-short-url::default.forward_query_params_helper'))
->default(false)
->inline(false),
DateTimePicker::make('expires_at')
->label(__('filament-short-url::default.expires_at'))
->nullable()
->native(false),
])->columns(2),
Section::make('Internal Notes')->schema([
Section::make(__('filament-short-url::default.form_section_validity'))
->schema([
Toggle::make('use_date_validity')
->label(__('filament-short-url::default.use_date_validity'))
->dehydrated(false)
->live()
->afterStateHydrated(function (Toggle $component, $state, Get $get, Set $set) {
$set('use_date_validity', $get('activated_at') !== null || $get('expires_at') !== null);
})
->afterStateUpdated(function ($state, Set $set) {
if ($state) {
$set('activated_at', now()->startOfMinute());
} else {
$set('activated_at', null);
$set('expires_at', null);
$set('expiration_redirect_url', null);
}
})
->columnSpanFull(),
DateTimePicker::make('activated_at')
->label(__('filament-short-url::default.activated_at'))
->nullable()
->native(false)
->withoutSeconds()
->live(onBlur: true)
->required(fn (Get $get): bool => (bool) $get('use_date_validity'))
->visible(fn (Get $get): bool => (bool) $get('use_date_validity'))
->minDate(now()->startOfDay())
->maxDate(fn (Get $get) => $get('expires_at')),
DateTimePicker::make('expires_at')
->label(__('filament-short-url::default.expires_at'))
->nullable()
->native(false)
->withoutSeconds()
->live(onBlur: true)
->visible(fn (Get $get): bool => (bool) $get('use_date_validity'))
->minDate(fn (Get $get) => $get('activated_at') ?: now()->startOfDay()),
TextInput::make('expiration_redirect_url')
->label(__('filament-short-url::default.expiration_redirect_url'))
->helperText(__('filament-short-url::default.expiration_redirect_url_helper'))
->url()
->maxLength(2048)
->nullable()
->visible(fn (Get $get): bool => (bool) $get('use_date_validity'))
->columnSpanFull(),
Toggle::make('single_use')
->label(__('filament-short-url::default.single_use'))
->helperText(__('filament-short-url::default.single_use_helper'))
->default(false)
->inline(false)
->live(),
TextInput::make('max_visits')
->label(__('filament-short-url::default.max_visits'))
->helperText(__('filament-short-url::default.max_visits_helper'))
->numeric()
->integer()
->minValue(1)
->nullable()
->hidden(fn (Get $get): bool => (bool) $get('single_use')),
])->columns(2),
Section::make(__('filament-short-url::default.form_section_notes'))->schema([
Textarea::make('notes')
->label(__('filament-short-url::default.notes'))
->rows(3)
@@ -177,57 +243,57 @@ class ShortUrlForm
return Tab::make(__('filament-short-url::default.tab_tracking'))
->icon('heroicon-o-chart-bar')
->schema([
Section::make('Visit Tracking')
Section::make(__('filament-short-url::default.form_section_tracking'))
->schema([
Toggle::make('track_visits')
->label(__('filament-short-url::default.track_visits'))
->default(true)
->default(fn () => config('filament-short-url.tracking.enabled', true))
->live()
->inline(false)
->columnSpanFull(),
])->columns(1),
Section::make('Tracked Fields')
Section::make(__('filament-short-url::default.form_section_tracked_fields'))
->schema([
Toggle::make('track_ip_address')
->label(__('filament-short-url::default.track_ip'))
->default(true)
->default(fn () => config('filament-short-url.tracking.fields.ip_address', true))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('track_visits')),
Toggle::make('track_browser')
->label(__('filament-short-url::default.track_browser'))
->default(true)
->default(fn () => config('filament-short-url.tracking.fields.browser', true))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('track_visits')),
Toggle::make('track_browser_version')
->label(__('filament-short-url::default.track_browser_version'))
->default(true)
->default(fn () => config('filament-short-url.tracking.fields.browser_version', true))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('track_visits')),
Toggle::make('track_operating_system')
->label(__('filament-short-url::default.track_os'))
->default(true)
->default(fn () => config('filament-short-url.tracking.fields.operating_system', true))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('track_visits')),
Toggle::make('track_operating_system_version')
->label(__('filament-short-url::default.track_os_version'))
->default(true)
->default(fn () => config('filament-short-url.tracking.fields.operating_system_version', true))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('track_visits')),
Toggle::make('track_device_type')
->label(__('filament-short-url::default.track_device_type'))
->default(true)
->default(fn () => config('filament-short-url.tracking.fields.device_type', true))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('track_visits')),
Toggle::make('track_referer_url')
->label(__('filament-short-url::default.track_referer'))
->default(true)
->default(fn () => config('filament-short-url.tracking.fields.referer_url', true))
->inline(false)
->disabled(fn (Get $get): bool => ! $get('track_visits')),
])
@@ -277,7 +343,7 @@ class ShortUrlForm
])
->columns(2),
Section::make('Third-Party Analytics')
Section::make(__('filament-short-url::default.form_section_analytics'))
->schema([
TextInput::make('ga_tracking_id')
->label(__('filament-short-url::default.ga_tracking_id'))
@@ -313,4 +379,152 @@ class ShortUrlForm
->dehydrated(false),
]);
}
private static function targetingTab(): Tab
{
return Tab::make(__('filament-short-url::default.tab_targeting'))
->icon('heroicon-o-shield-check')
->schema([
Section::make(__('filament-short-url::default.security_section_title'))
->schema([
TextInput::make('password')
->label(__('filament-short-url::default.password'))
->helperText(__('filament-short-url::default.password_helper'))
->password()
->revealable()
->nullable()
->maxLength(255),
Toggle::make('show_warning_page')
->label(__('filament-short-url::default.show_warning_page'))
->helperText(__('filament-short-url::default.show_warning_page_helper'))
->default(false)
->inline(false),
])->columns(2),
Section::make(__('filament-short-url::default.targeting_type'))
->schema([
Select::make('targeting_rules.type')
->label(__('filament-short-url::default.targeting_type'))
->options([
'none' => __('filament-short-url::default.targeting_type_none'),
'device' => __('filament-short-url::default.targeting_type_device'),
'geo' => __('filament-short-url::default.targeting_type_country'),
'rotation' => __('filament-short-url::default.targeting_type_rotation'),
])
->default('none')
->live()
->required(),
Section::make(__('filament-short-url::default.device_targeting_rules'))
->schema([
TextInput::make('targeting_rules.device.mobile')
->label(__('filament-short-url::default.device_mobile'))
->url()
->nullable()
->maxLength(2048),
TextInput::make('targeting_rules.device.tablet')
->label(__('filament-short-url::default.device_tablet'))
->url()
->nullable()
->maxLength(2048),
TextInput::make('targeting_rules.device.desktop')
->label(__('filament-short-url::default.device_desktop'))
->url()
->nullable()
->maxLength(2048),
])
->columns(1)
->visible(fn (Get $get): bool => $get('targeting_rules.type') === 'device'),
Repeater::make('targeting_rules.geo')
->label(__('filament-short-url::default.country_targeting_rules'))
->schema([
Select::make('country_code')
->label(__('filament-short-url::default.country_code'))
->options(function (): array {
$countries = __('filament-short-url::countries');
if (is_array($countries)) {
asort($countries, SORT_LOCALE_STRING);
return $countries;
}
return [];
})
->searchable()
->optionsLimit(300)
->disableOptionsWhenSelectedInSiblingRepeaterItems()
->required(),
TextInput::make('url')
->label(__('filament-short-url::default.destination_url'))
->url()
->required()
->maxLength(2048),
])
->columns(2)
->visible(fn (Get $get): bool => $get('targeting_rules.type') === 'geo'),
Repeater::make('targeting_rules.rotation')
->label(__('filament-short-url::default.rotation_targeting_rules'))
->schema([
TextInput::make('url')
->label(__('filament-short-url::default.rotation_url'))
->url()
->required()
->maxLength(2048),
TextInput::make('weight')
->label(__('filament-short-url::default.rotation_weight'))
->helperText(__('filament-short-url::default.rotation_weight_helper'))
->numeric()
->integer()
->minValue(1)
->maxValue(1000)
->required()
->default(50),
])
->columns(2)
->visible(fn (Get $get): bool => $get('targeting_rules.type') === 'rotation'),
]),
]);
}
private static function marketingTab(): Tab
{
return Tab::make(__('filament-short-url::default.tab_marketing'))
->icon('heroicon-o-megaphone')
->schema([
Section::make(__('filament-short-url::default.marketing_pixels_title'))
->description(__('filament-short-url::default.marketing_pixels_desc'))
->schema([
TextInput::make('pixel_meta_id')
->label(__('filament-short-url::default.pixel_meta'))
->placeholder('e.g., 1234567890')
->maxLength(100)
->nullable(),
TextInput::make('pixel_google_id')
->label(__('filament-short-url::default.pixel_google'))
->placeholder('e.g., G-XXXXXXXXXX or AW-XXXXXXXXXX')
->maxLength(100)
->nullable(),
TextInput::make('pixel_linkedin_id')
->label(__('filament-short-url::default.pixel_linkedin'))
->placeholder('e.g., 1234567')
->maxLength(100)
->nullable(),
])->columns(3),
Section::make(__('filament-short-url::default.marketing_webhooks_title'))
->description(__('filament-short-url::default.marketing_webhooks_desc'))
->schema([
TextInput::make('webhook_url')
->label(__('filament-short-url::default.webhook_url'))
->placeholder('https://api.yourcrm.com/webhooks/clicks')
->url()
->maxLength(2048)
->nullable()
->columnSpanFull(),
]),
]);
}
}

View File

@@ -2,19 +2,21 @@
namespace Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Tables;
use Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource;
use Bjanczak\FilamentShortUrl\Models\ShortUrl;
use Filament\Actions\Action;
use Filament\Actions\BulkAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\IconColumn;
use Filament\Forms;
use Filament\Tables\Columns\Layout\Stack;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;
class ShortUrlsTable
{
@@ -22,60 +24,147 @@ class ShortUrlsTable
{
return $table
->columns([
TextColumn::make('url_key')
->label(__('filament-short-url::default.col_short_url'))
->getStateUsing(fn (ShortUrl $record): string => $record->getShortUrl())
->copyable()
->copyMessage(__('filament-short-url::default.qr_copied'))
->fontFamily('mono')
->weight(FontWeight::SemiBold)
->searchable(query: fn ($query, string $search) => $query->where('url_key', 'like', "%{$search}%")),
Stack::make([
// ROW 1: Favicon + Short URL with copy capability on click of text or icon (vertically centered!)
TextColumn::make('url_key')
->label(__('filament-short-url::default.col_short_url'))
->getStateUsing(static function (ShortUrl $record): HtmlString {
$shortUrl = e($record->getShortUrl());
$copiedMsg = e(__('filament-short-url::default.qr_copied'));
$tooltipCopy = e(__('filament-short-url::default.action_copy'));
$destHost = e(parse_url($record->destination_url, PHP_URL_HOST));
TextColumn::make('destination_url')
->label(__('filament-short-url::default.col_destination_url'))
->limit(45)
->tooltip(fn (ShortUrl $record): string => $record->destination_url)
->url(fn (ShortUrl $record): string => $record->destination_url, shouldOpenInNewTab: true)
->searchable(),
return new HtmlString(<<<HTML
<div onclick="
event.preventDefault();
event.stopPropagation();
const text = '{$shortUrl}';
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(text);
} else {
const textCopyArea = document.createElement('textarea');
textCopyArea.value = text;
textCopyArea.style.position = 'fixed';
textCopyArea.style.left = '-999999px';
textCopyArea.style.top = '-999999px';
document.body.appendChild(textCopyArea);
textCopyArea.focus();
textCopyArea.select();
try {
document.execCommand('copy');
} catch (err) {}
textCopyArea.remove();
}
if (typeof FilamentNotification !== 'undefined') {
new FilamentNotification()
.title('{$copiedMsg}')
.success()
.send();
} else if (window.Alpine) {
window.Alpine.store('filament-notifications')?.send({
status: 'success',
title: '{$copiedMsg}'
});
}
" class="flex items-center gap-3 cursor-pointer w-fit">
<div class="flex items-center justify-center rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-1.5 flex-shrink-0 w-8 h-8">
<img src="https://icons.duckduckgo.com/ip2/{$destHost}.ico"
class="w-full h-full object-contain"
onerror="this.src='https://heroicons.com/24/outline/link.svg'" />
</div>
<span class="text-[#2a5bd7] text-[16px] font-bold leading-6 break-all line-clamp-1">
{$shortUrl}
</span>
<span title="{$tooltipCopy}" class="w-8 h-8 rounded-full flex items-center justify-center bg-[#f4f4f5] hover:bg-[#e4e4e7] dark:bg-gray-800 dark:hover:bg-gray-700 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors flex-shrink-0 focus:outline-none">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</span>
</div>
HTML
);
})
->searchable(query: fn ($query, string $search) => $query->where('url_key', 'like', "%{$search}%")),
TextColumn::make('total_visits')
->label(__('filament-short-url::default.col_total_visits'))
->numeric()
->badge()
->color('gray')
->sortable(),
// ROW 2: Sub-arrow + Destination URL
TextColumn::make('destination_url')
->label(__('filament-short-url::default.col_destination_url'))
->getStateUsing(fn ($record): HtmlString => new HtmlString('
<div class="flex items-center gap-1.5 text-gray-500 dark:text-gray-400 text-xs mt-2">
<svg class="w-3.5 h-3.5 flex-shrink-0 text-gray-400 dark:text-gray-500"
style="transform: scaleY(-1);"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="2.5"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M15 15l6-6m0 0l-6-6m6 6H9a6 6 0 00-6 6v3" />
</svg>
<a href="'.e($record->destination_url).'"
target="_blank"
rel="noopener noreferrer"
class="truncate max-w-[50ch] hover:underline text-[#273144] text-[15px] leading-[16px] font-medium"
title="'.e($record->destination_url).'">
'.e($record->destination_url).'
</a>
</div>
'))
->searchable(),
TextColumn::make('unique_visits')
->label(__('filament-short-url::default.stats_card_unique'))
->numeric()
->badge()
->color('info')
->sortable(),
// ROW 3: Bottom Metadata (Total clicks / Unique clicks / Date added / Expiry / Redirect code)
TextColumn::make('metadata_badges')
->getStateUsing(fn ($record): HtmlString => new HtmlString('
<div class="flex flex-wrap items-center gap-2 text-xs text-gray-500 dark:text-gray-400 mt-3">
<!-- Clicks Badge -->
<span class="inline-flex items-center gap-1 bg-[#f4f4f5] dark:bg-gray-800 px-2 py-1 rounded text-[11px] font-medium text-gray-600 dark:text-gray-300">
<svg class="w-3.5 h-3.5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
<path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
</svg>
'.$record->total_visits.' clicks
</span>
ToggleColumn::make('is_enabled')
->label(__('filament-short-url::default.col_status'))
->sortable(),
<!-- Unique Clicks Badge -->
<span class="inline-flex items-center gap-1 bg-[#f4f4f5] dark:bg-gray-800 px-2 py-1 rounded text-[11px] font-medium text-gray-600 dark:text-gray-300">
<svg class="w-3.5 h-3.5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>
'.$record->unique_visits.' unique
</span>
IconColumn::make('track_visits')
->label(__('filament-short-url::default.track_visits'))
->boolean()
->trueIcon('heroicon-o-signal')
->falseIcon('heroicon-o-signal-slash')
->trueColor('success')
->falseColor('gray'),
<!-- Date Added Badge -->
<span class="inline-flex items-center gap-1 bg-[#f4f4f5] dark:bg-gray-800 px-2 py-1 rounded text-[11px] font-medium text-gray-600 dark:text-gray-300">
<svg class="w-3.5 h-3.5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
'.$record->created_at->format('M d, Y').'
</span>
TextColumn::make('expires_at')
->label(__('filament-short-url::default.col_expires_at'))
->dateTime('d M Y')
->placeholder('Never')
->color(fn (ShortUrl $record): string => $record->isExpired() ? 'danger' : 'gray')
->sortable(),
<!-- Expiry / Single Use Badge -->
<span class="inline-flex items-center gap-1 bg-[#f4f4f5] dark:bg-gray-800 px-2 py-1 rounded text-[11px] font-medium text-gray-600 dark:text-gray-300">
'.($record->expires_at ? '
<svg class="w-3.5 h-3.5 text-yellow-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
Expires: '.$record->expires_at->format('M d, Y').'
' : '
<svg class="w-3.5 h-3.5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
</svg>
No expiry
').'
</span>
TextColumn::make('created_at')
->label(__('filament-short-url::default.col_created_at'))
->since()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
<!-- Redirect Type Badge -->
<span class="inline-flex items-center gap-1 bg-[#f4f4f5] dark:bg-gray-800 px-2 py-1 rounded text-[11px] font-medium text-gray-600 dark:text-gray-300">
<svg class="w-3.5 h-3.5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
</svg>
'.$record->redirect_status_code.' redirect
</span>
</div>
')),
]),
])
->filters([
TernaryFilter::make('is_enabled')
@@ -95,43 +184,150 @@ class ShortUrlsTable
'1' => 'Single-use',
]),
])
->recordActions([
->recordClasses(fn (): string => 'short-url-card')
->actions([
Action::make('share')
->label(__('filament-short-url::default.action_share'))
->icon('heroicon-o-share')
->color('gray')
->iconButton()
->tooltip(__('filament-short-url::default.action_share'))
->modalHeading(__('filament-short-url::default.share_title'))
->modalWidth('md')
->modalSubmitAction(false)
->modalCancelAction(false)
->form([
Forms\Components\Placeholder::make('platforms')
->label(__('filament-short-url::default.share_description'))
->content(fn (ShortUrl $record): HtmlString => new HtmlString('
<div class="flex items-center gap-6 overflow-x-auto pb-4 pt-1 scroll-smooth" style="scrollbar-width: thin; -ms-overflow-style: none;">
<!-- Messenger -->
<a href="fb-messenger://share/?link='.urlencode($record->getShortUrl()).'" target="_blank" rel="noopener noreferrer" class="flex flex-col items-center gap-2 group flex-shrink-0 cursor-pointer">
<div class="w-11 h-11 rounded-full bg-gradient-to-tr from-[#006aff] via-[#00b2ff] to-[#00d6ff] text-white flex items-center justify-center shadow-sm group-hover:scale-105 transition-transform duration-200">
<svg class="w-5.5 h-5.5" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 2C6.48 2 2 6.14 2 11.25c0 2.9 1.45 5.48 3.73 7.08v3.67c0 .24.23.4.43.27l4.07-2.3c.57.16 1.17.25 1.77.25 5.52 0 10-4.14 10-9.25S17.52 2 12 2zm1.09 11.95l-2.43-2.6-4.73 2.6 5.19-5.52 2.47 2.63 4.7-2.63-5.2 5.52z"/>
</svg>
</div>
<span class="text-[11px] font-medium text-gray-500 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-white transition-colors">Messenger</span>
</a>
<!-- Facebook -->
<a href="https://www.facebook.com/sharer/sharer.php?u='.urlencode($record->getShortUrl()).'" target="_blank" rel="noopener noreferrer" class="flex flex-col items-center gap-2 group flex-shrink-0 cursor-pointer">
<div class="w-11 h-11 rounded-full bg-[#1877f2] text-white flex items-center justify-center shadow-sm group-hover:scale-105 transition-transform duration-200">
<svg class="w-5.5 h-5.5" fill="currentColor" viewBox="0 0 24 24">
<path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
</svg>
</div>
<span class="text-[11px] font-medium text-gray-550 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-white transition-colors">Facebook</span>
</a>
<!-- WhatsApp -->
<a href="https://api.whatsapp.com/send?text='.urlencode($record->getShortUrl()).'" target="_blank" rel="noopener noreferrer" class="flex flex-col items-center gap-2 group flex-shrink-0 cursor-pointer">
<div class="w-11 h-11 rounded-full bg-[#25d366] text-white flex items-center justify-center shadow-sm group-hover:scale-105 transition-transform duration-200">
<svg class="w-5.5 h-5.5" fill="currentColor" viewBox="0 0 24 24">
<path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L0 24l6.335-1.662c1.746.953 3.71 1.458 5.704 1.459h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
</svg>
</div>
<span class="text-[11px] font-medium text-gray-500 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-white transition-colors">WhatsApp</span>
</a>
<!-- Twitter/X -->
<a href="https://twitter.com/intent/tweet?url='.urlencode($record->getShortUrl()).'" target="_blank" rel="noopener noreferrer" class="flex flex-col items-center gap-2 group flex-shrink-0 cursor-pointer">
<div class="w-11 h-11 rounded-full bg-[#0f1419] text-white flex items-center justify-center shadow-sm group-hover:scale-105 transition-transform duration-200">
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
<path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
</svg>
</div>
<span class="text-[11px] font-medium text-gray-500 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-white transition-colors">Twitter (X)</span>
</a>
<!-- LinkedIn -->
<a href="https://www.linkedin.com/sharing/share-offsite/?url='.urlencode($record->getShortUrl()).'" target="_blank" rel="noopener noreferrer" class="flex flex-col items-center gap-2 group flex-shrink-0 cursor-pointer">
<div class="w-11 h-11 rounded-full bg-[#0077b5] text-white flex items-center justify-center shadow-sm group-hover:scale-105 transition-transform duration-200">
<svg class="w-5.5 h-5.5" fill="currentColor" viewBox="0 0 24 24">
<path d="M19 0h-14c-2.761 0-5 2.239-5 5v14c0 2.761 2.239 5 5 5h14c2.762 0 5-2.239 5-5v-14c0-2.761-2.238-5-5-5zm-11 19h-3v-11h3v11zm-1.5-12.268c-.966 0-1.75-.779-1.75-1.75s.784-1.75 1.75-1.75 1.75.779 1.75 1.75-.784 1.75-1.75 1.75zm13.5 12.268h-3v-5.604c0-3.368-4-3.113-4 0v5.604h-3v-11h3v1.765c1.396-2.586 7-2.777 7 2.476v6.759z"/>
</svg>
</div>
<span class="text-[11px] font-medium text-gray-500 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-white transition-colors">LinkedIn</span>
</a>
<!-- Email -->
<a href="mailto:?body='.urlencode($record->getShortUrl()).'" target="_blank" rel="noopener noreferrer" class="flex flex-col items-center gap-2 group flex-shrink-0 cursor-pointer">
<div class="w-11 h-11 rounded-full bg-[#6b7280] text-white flex items-center justify-center shadow-sm group-hover:scale-105 transition-transform duration-200">
<svg class="w-5.5 h-5.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
</div>
<span class="text-[11px] font-medium text-gray-500 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-white transition-colors">Email</span>
</a>
</div>
')),
Forms\Components\Placeholder::make('copy_field')
->label('')
->content(fn (ShortUrl $record): HtmlString => new HtmlString('
<div class="flex items-center gap-2 relative mt-2">
<input type="text"
readonly
value="'.e($record->getShortUrl()).'"
id="share_link_input_'.$record->id.'"
class="flex-1 min-w-0 block w-full px-3.5 py-2.5 rounded-lg border border-gray-300 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 text-gray-900 dark:text-gray-100 text-sm focus:ring-primary-500 focus:border-primary-500 dark:focus:ring-primary-400 dark:focus:border-primary-400 focus:outline-none">
<button onclick="
const input = document.getElementById(\'share_link_input_'.$record->id.'\');
input.select();
navigator.clipboard.writeText(input.value);
if (typeof FilamentNotification !== \'undefined\') {
new FilamentNotification()
.title(\''.e(__('filament-short-url::default.share_copied')).'\')
.success()
.send();
} else if (typeof Alpine !== \'undefined\') {
Alpine.store(\'filament-notifications\')?.send({
status: \'success\',
title: \''.e(__('filament-short-url::default.share_copied')).'\'
});
}
"
class="flex-shrink-0 inline-flex items-center justify-center gap-1.5 px-4 py-2.5 bg-gray-900 hover:bg-gray-800 dark:bg-gray-100 dark:hover:bg-white text-white dark:text-gray-950 font-semibold text-sm rounded-lg shadow-sm hover:shadow transition duration-200">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
<span>'.e(__('filament-short-url::default.share_copy')).'</span>
</button>
</div>
')),
]),
Action::make('stats')
->label(__('filament-short-url::default.action_stats'))
->icon('heroicon-o-chart-bar')
->color('gray')
->size('sm')
->url(fn (ShortUrl $record): string => route(
'filament.admin.resources.short-urls.stats',
['record' => $record->id]
)),
Action::make('copy')
->label(__('filament-short-url::default.action_copy'))
->icon('heroicon-o-clipboard')
->color('gray')
->size('sm')
->action(fn () => null) // Copy happens client-side
->extraAttributes(fn (ShortUrl $record): array => [
'x-on:click' => 'navigator.clipboard.writeText("'.$record->getShortUrl().'")',
'title' => 'Copy short URL',
]),
->iconButton()
->tooltip(__('filament-short-url::default.action_stats'))
->url(fn (ShortUrl $record): string => ShortUrlResource::getUrl('stats', ['record' => $record])),
EditAction::make()
->icon('heroicon-o-pencil-square')
->size('sm')
->color('gray'),
->color('gray')
->iconButton()
->tooltip(__('filament-short-url::default.action_edit')),
DeleteAction::make()
->icon('heroicon-o-trash')
->color('gray')
->iconButton()
->tooltip(__('filament-short-url::default.action_delete')),
])
->contentGrid([
'md' => 1,
'xl' => 1,
])
->toolbarActions([
BulkActionGroup::make([
BulkAction::make('enable')
->label('Enable selected')
->label(__('filament-short-url::default.action_enable_selected'))
->icon('heroicon-o-check-circle')
->action(fn ($records) => $records->each->update(['is_enabled' => true]))
->deselectRecordsAfterCompletion(),
BulkAction::make('disable')
->label('Disable selected')
->label(__('filament-short-url::default.action_disable_selected'))
->icon('heroicon-o-x-circle')
->action(fn ($records) => $records->each->update(['is_enabled' => false]))
->deselectRecordsAfterCompletion(),

View File

@@ -0,0 +1,125 @@
<?php
namespace Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets;
use Bjanczak\FilamentShortUrl\Models\ShortUrl;
use Bjanczak\FilamentShortUrl\Models\ShortUrlVisit;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class ShortUrlGlobalOverview extends BaseWidget
{
/** Disable automatic Livewire polling — cache is invalidated via model events instead. */
protected ?string $pollingInterval = null;
protected int|string|array $columnSpan = 'full';
/** Cache key for link counts (forever, busted on create/delete). */
public const LINKS_CACHE_KEY = 'filament-short-url:global-links';
/** Cache key for click trends (short TTL, time-based data). */
public const CLICKS_CACHE_KEY = 'filament-short-url:global-clicks';
protected function getStats(): array
{
$linkData = $this->getLinkStats();
$clickData = $this->getClickStats();
$clicksTrend = $clickData['prev7Clicks'] > 0
? round((($clickData['last7Clicks'] - $clickData['prev7Clicks']) / $clickData['prev7Clicks']) * 100, 1)
: ($clickData['last7Clicks'] > 0 ? 100.0 : 0.0);
$uniquesTrend = $clickData['prev7Uniques'] > 0
? round((($clickData['last7Uniques'] - $clickData['prev7Uniques']) / $clickData['prev7Uniques']) * 100, 1)
: ($clickData['last7Uniques'] > 0 ? 100.0 : 0.0);
return [
Stat::make(__('filament-short-url::default.navigation_label'), number_format($linkData['totalLinks']))
->description($linkData['activeLinks'].' active · '.$linkData['activeRatio'].'%')
->descriptionIcon('heroicon-m-link')
->icon('heroicon-o-link')
->color('gray'),
Stat::make(__('filament-short-url::default.stats_card_total'), number_format($clickData['totalVisits']))
->description(abs($clicksTrend).'% '.($clicksTrend >= 0 ? 'up' : 'down').' vs last 7 days')
->descriptionIcon($clicksTrend >= 0 ? 'heroicon-m-arrow-trending-up' : 'heroicon-m-arrow-trending-down')
->icon('heroicon-o-cursor-arrow-rays')
->color($clicksTrend >= 0 ? 'success' : 'danger'),
Stat::make(__('filament-short-url::default.stats_card_unique'), number_format($clickData['uniqueVisits']))
->description(abs($uniquesTrend).'% '.($uniquesTrend >= 0 ? 'up' : 'down').' vs last 7 days')
->descriptionIcon($uniquesTrend >= 0 ? 'heroicon-m-arrow-trending-up' : 'heroicon-m-arrow-trending-down')
->icon('heroicon-o-user-group')
->color($uniquesTrend >= 0 ? 'success' : 'danger'),
];
}
/**
* Link counts cached forever — invalidated only when a ShortUrl is created or deleted.
*
* @return array{totalLinks: int, activeLinks: int, activeRatio: int}
*/
protected function getLinkStats(): array
{
return Cache::rememberForever(self::LINKS_CACHE_KEY, function () {
$agg = ShortUrl::query()
->select([
DB::raw('COUNT(*) as total'),
DB::raw('SUM(CASE WHEN is_enabled THEN 1 ELSE 0 END) as active'),
])
->first();
$total = (int) ($agg->total ?? 0);
$active = (int) ($agg->active ?? 0);
return [
'totalLinks' => $total,
'activeLinks' => $active,
'activeRatio' => $total > 0 ? round(($active / $total) * 100) : 0,
];
});
}
/**
* Click/visit stats cached with a short TTL (time-based data changes frequently).
*
* @return array{totalVisits: int, uniqueVisits: int, last7Clicks: int, prev7Clicks: int, last7Uniques: int, prev7Uniques: int}
*/
protected function getClickStats(): array
{
$ttl = (int) config('filament-short-url.geo_ip.stats_cache_ttl', 300);
return Cache::remember(self::CLICKS_CACHE_KEY, $ttl, function () {
$agg = ShortUrl::query()
->select([
DB::raw('SUM(total_visits) as total_visits'),
DB::raw('SUM(unique_visits) as unique_visits'),
])
->first();
$last7Clicks = ShortUrlVisit::where('visited_at', '>=', now()->subDays(7))->count();
$prev7Clicks = ShortUrlVisit::where('visited_at', '>=', now()->subDays(14))
->where('visited_at', '<', now()->subDays(7))
->count();
$last7Uniques = ShortUrlVisit::where('visited_at', '>=', now()->subDays(7))
->distinct('ip_hash')
->count('ip_hash');
$prev7Uniques = ShortUrlVisit::whereBetween('visited_at', [now()->subDays(14), now()->subDays(7)])
->distinct('ip_hash')
->count('ip_hash');
return [
'totalVisits' => (int) ($agg->total_visits ?? 0),
'uniqueVisits' => (int) ($agg->unique_visits ?? 0),
'last7Clicks' => $last7Clicks,
'prev7Clicks' => $prev7Clicks,
'last7Uniques' => $last7Uniques,
'prev7Uniques' => $prev7Uniques,
];
});
}
}

View File

@@ -10,13 +10,27 @@ class ShortUrlStatsOverview extends BaseWidget
{
public ?ShortUrl $record = null;
public ?string $dateFrom = null;
public ?string $dateTo = null;
protected function getStats(): array
{
if (! $this->record) {
return [];
}
$stats = $this->record->getCachedStats();
$stats = $this->record->getCachedStats($this->dateFrom, $this->dateTo);
$topSource = 'Direct';
if (! empty($stats['utmSources'])) {
$topSource = array_key_first($stats['utmSources']);
}
$topCountry = '—';
if (! empty($stats['visitsByCountry'])) {
$topCountry = array_key_first($stats['visitsByCountry']);
}
return [
Stat::make(__('filament-short-url::default.stats_card_total'), number_format($stats['totalVisits'] ?? 0))
@@ -27,17 +41,13 @@ class ShortUrlStatsOverview extends BaseWidget
->icon('heroicon-o-user-group')
->color('info'),
Stat::make(__('filament-short-url::default.stats_card_today'), number_format($stats['visitsToday'] ?? 0))
->icon('heroicon-o-sun')
Stat::make(__('filament-short-url::default.stats_card_top_source'), $topSource)
->icon('heroicon-o-megaphone')
->color('warning'),
Stat::make(__('filament-short-url::default.stats_card_week'), number_format($stats['visitsThisWeek'] ?? 0))
->icon('heroicon-o-calendar-days')
Stat::make(__('filament-short-url::default.stats_card_top_country'), $topCountry)
->icon('heroicon-o-globe-alt')
->color('success'),
Stat::make(__('filament-short-url::default.stats_card_month'), number_format($stats['visitsThisMonth'] ?? 0))
->icon('heroicon-o-calendar')
->color('gray'),
];
}
}

View File

@@ -9,6 +9,10 @@ class ShortUrlVisitsBottomBreakdown extends Widget
{
public ?ShortUrl $record = null;
public ?string $dateFrom = null;
public ?string $dateTo = null;
protected string $view = 'filament-short-url::widgets.visits-bottom-breakdown';
protected int|string|array $columnSpan = 'full';
@@ -29,17 +33,25 @@ class ShortUrlVisitsBottomBreakdown extends Widget
'visitsByBrowser' => [],
'visitsByOs' => [],
'visitsByReferer' => [],
'visitsByCity' => [],
'utmSources' => [],
'utmMediums' => [],
'utmCampaigns' => [],
'totalVisits' => 0,
];
}
$stats = $this->record->getCachedStats();
$stats = $this->record->getCachedStats($this->dateFrom, $this->dateTo);
return [
'visitsByDevice' => $stats['visitsByDevice'] ?? [],
'visitsByBrowser' => $stats['visitsByBrowser'] ?? [],
'visitsByOs' => $stats['visitsByOs'] ?? [],
'visitsByReferer' => $stats['visitsByReferer'] ?? [],
'visitsByCity' => $stats['visitsByCity'] ?? [],
'utmSources' => $stats['utmSources'] ?? [],
'utmMediums' => $stats['utmMediums'] ?? [],
'utmCampaigns' => $stats['utmCampaigns'] ?? [],
'totalVisits' => $stats['totalVisits'] ?? 0,
];
}

View File

@@ -9,6 +9,10 @@ class ShortUrlVisitsChart extends ChartWidget
{
public ?ShortUrl $record = null;
public ?string $dateFrom = null;
public ?string $dateTo = null;
protected ?string $maxHeight = '200px';
protected int|string|array $columnSpan = [
@@ -29,7 +33,7 @@ class ShortUrlVisitsChart extends ChartWidget
];
}
$stats = $this->record->getCachedStats();
$stats = $this->record->getCachedStats($this->dateFrom, $this->dateTo);
$visitsByDay = $stats['visitsByDay'] ?? [];
return [
@@ -46,7 +50,17 @@ class ShortUrlVisitsChart extends ChartWidget
'fill' => true,
],
],
'labels' => array_keys($visitsByDay),
'labels' => array_map(function (string $date) {
try {
$carbon = \Illuminate\Support\Carbon::parse($date);
if (strlen($date) === 7) { // Y-m
return $carbon->format('m.Y');
}
return $carbon->format('d.m');
} catch (\Throwable $e) {
return $date;
}
}, array_keys($visitsByDay)),
];
}

View File

@@ -9,6 +9,10 @@ class ShortUrlVisitsRightBreakdown extends Widget
{
public ?ShortUrl $record = null;
public ?string $dateFrom = null;
public ?string $dateTo = null;
protected string $view = 'filament-short-url::widgets.visits-right-breakdown';
protected int|string|array $columnSpan = [
@@ -32,7 +36,7 @@ class ShortUrlVisitsRightBreakdown extends Widget
];
}
$stats = $this->record->getCachedStats();
$stats = $this->record->getCachedStats($this->dateFrom, $this->dateTo);
return [
'visitsByCountry' => $stats['visitsByCountry'] ?? [],

View File

@@ -0,0 +1,99 @@
<?php
namespace Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets;
use Bjanczak\FilamentShortUrl\Models\ShortUrl;
use Bjanczak\FilamentShortUrl\Models\ShortUrlVisit;
use Filament\Widgets\Widget;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class ShortUrlWorldMapWidget extends Widget
{
public ?ShortUrl $record = null;
public ?string $dateFrom = null;
public ?string $dateTo = null;
protected string $view = 'filament-short-url::widgets.world-map';
protected int|string|array $columnSpan = 'full';
public function mount(?ShortUrl $record = null): void
{
$this->record = $record;
}
/**
* Build a country_code → visit count map, merging daily stats and today's raw visits.
*
* @return array<string, int>
*/
public function getCountryData(): array
{
if (! $this->record) {
return [];
}
$dateFromClean = $this->dateFrom ? Carbon::parse($this->dateFrom)->toDateString() : null;
$dateToClean = $this->dateTo ? Carbon::parse($this->dateTo)->toDateString() : null;
$today = Carbon::today()->toDateString();
$cacheTtl = (int) config('filament-short-url.geo_ip.stats_cache_ttl', 300);
$cacheKey = "short_url_world_map_{$this->record->id}_".($dateFromClean ?: 'all').'_'.($dateToClean ?: 'all');
return cache()->remember($cacheKey, $cacheTtl, function () use ($dateFromClean, $dateToClean) {
$counts = [];
$query = ShortUrlVisit::query()
->select('country_code', DB::raw('COUNT(*) as cnt'))
->where('short_url_id', $this->record->id)
->whereNotNull('country_code')
->where('country_code', '!=', '')
->where('is_bot', false)
->where('is_proxy', false);
if ($dateFromClean) {
$query->whereDate('visited_at', '>=', $dateFromClean);
}
if ($dateToClean) {
$query->whereDate('visited_at', '<=', $dateToClean);
}
foreach ($query->groupBy('country_code')->get() as $row) {
$code = strtoupper(trim($row->country_code));
if ($code) {
$counts[$code] = (int) $row->cnt;
}
}
arsort($counts);
return $counts;
});
}
/**
* @return array<string, mixed>
*/
protected function getViewData(): array
{
$countryData = $this->getCountryData();
$max = max(1, ...array_values($countryData) ?: [1]);
$total = array_sum($countryData);
// Normalise to 0100 for CSS opacity/intensity
$normalized = [];
foreach ($countryData as $code => $count) {
$normalized[$code] = round(($count / $max) * 100);
}
return [
'countryData' => $countryData,
'maxCount' => $max,
'totalClicks' => $total,
'normalized' => $normalized,
];
}
}

View File

@@ -12,6 +12,10 @@ class FilamentShortUrlPlugin implements Plugin
protected ?int $navigationSort = null;
protected ?string $navigationLabel = null;
protected ?string $navigationIcon = null;
protected ?string $routePrefix = null;
// ─── Factory ─────────────────────────────────────────────────────────────
@@ -67,6 +71,8 @@ class FilamentShortUrlPlugin implements Plugin
/**
* Set the navigation sort order.
*
* @example FilamentShortUrlPlugin::make()->navigationSort(50)
*/
public function navigationSort(int $sort): static
{
@@ -79,4 +85,38 @@ class FilamentShortUrlPlugin implements Plugin
{
return $this->navigationSort;
}
/**
* Override the navigation label (menu item name).
*
* @example FilamentShortUrlPlugin::make()->navigationLabel('Short Links')
*/
public function navigationLabel(string $label): static
{
$this->navigationLabel = $label;
return $this;
}
public function getNavigationLabel(): ?string
{
return $this->navigationLabel;
}
/**
* Override the navigation icon.
*
* @example FilamentShortUrlPlugin::make()->navigationIcon('heroicon-o-link')
*/
public function navigationIcon(string $icon): static
{
$this->navigationIcon = $icon;
return $this;
}
public function getNavigationIcon(): ?string
{
return $this->navigationIcon;
}
}

View File

@@ -2,11 +2,15 @@
namespace Bjanczak\FilamentShortUrl;
use Bjanczak\FilamentShortUrl\Console\Commands\SyncBufferedCountersCommand;
use Bjanczak\FilamentShortUrl\Services\GeoIpService;
use Bjanczak\FilamentShortUrl\Services\ShortUrlService;
use Bjanczak\FilamentShortUrl\Services\ShortUrlSettingsManager;
use Bjanczak\FilamentShortUrl\Services\ShortUrlTracker;
use Bjanczak\FilamentShortUrl\Services\UserAgentParser;
use Filament\Support\Assets\Css;
use Filament\Support\Facades\FilamentAsset;
use Illuminate\Console\Scheduling\Schedule;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;
@@ -24,6 +28,16 @@ class FilamentShortUrlServiceProvider extends PackageServiceProvider
->hasMigrations([
'2024_01_01_000001_create_short_urls_table',
'2024_01_01_000002_create_short_url_visits_table',
'2026_06_01_000003_add_utm_city_referer_to_short_url_visits_table',
'2026_06_01_000004_add_targeting_and_security_to_short_urls_table',
'2026_06_01_000005_create_short_url_daily_stats_table',
'2026_06_02_000006_add_max_visits_and_expiration_redirect_to_short_urls_table',
'2026_06_02_000007_add_retargeting_pixels_and_webhooks_to_short_urls_table',
'2026_06_02_000008_add_bot_and_proxy_to_short_url_visits_table',
])
->hasCommands([
SyncBufferedCountersCommand::class,
Console\Commands\AggregateAndPruneVisitsCommand::class,
])
->hasRoutes(['web']);
}
@@ -38,5 +52,27 @@ class FilamentShortUrlServiceProvider extends PackageServiceProvider
$this->app->singleton(GeoIpService::class);
$this->app->singleton(ShortUrlService::class);
$this->app->singleton(ShortUrlTracker::class);
$this->app->singleton(\Bjanczak\FilamentShortUrl\Services\ProxyDetectionService::class);
$this->app->singleton(\Bjanczak\FilamentShortUrl\Services\SafeBrowsingService::class);
}
public function packageBooted(): void
{
FilamentAsset::register([
Css::make('filament-short-url', __DIR__.'/../resources/dist/filament-short-url.css'),
], package: 'janczakb/filament-short-url');
// Automatically register scheduled tasks in the application scheduler
$this->app->booted(function (): void {
$schedule = $this->app->make(Schedule::class);
if (config('filament-short-url.pruning.enabled', true)) {
$schedule->command('short-url:aggregate-and-prune')->dailyAt('02:00');
}
if (config('filament-short-url.counter_buffering.enabled', false)) {
$schedule->command('short-url:sync-counters')->everyMinute();
}
});
}
}

View File

@@ -0,0 +1,145 @@
<?php
namespace Bjanczak\FilamentShortUrl\Http\Controllers;
use Bjanczak\FilamentShortUrl\Jobs\SendWebhookJob;
use Bjanczak\FilamentShortUrl\Models\ShortUrl;
use Bjanczak\FilamentShortUrl\Services\ShortUrlService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Log;
class ShortUrlApiController extends Controller
{
public function __construct(
private readonly ShortUrlService $service
) {}
/**
* Display a listing of short URLs.
*/
public function index(): JsonResponse
{
$links = ShortUrl::orderBy('id', 'desc')->paginate(30);
$transformed = $links->getCollection()->map(fn ($link) => $this->transformLink($link));
return response()->json([
'data' => $transformed,
'meta' => [
'current_page' => $links->currentPage(),
'last_page' => $links->lastPage(),
'per_page' => $links->perPage(),
'total' => $links->total(),
],
]);
}
/**
* Store a newly created short URL.
*/
public function store(Request $request): JsonResponse
{
$validated = $request->validate([
'destination_url' => 'required|url|max:2048',
'url_key' => 'nullable|string|alpha_dash|max:50|unique:short_urls,url_key',
'notes' => 'nullable|string|max:1000',
'is_enabled' => 'nullable|boolean',
'redirect_status_code' => 'nullable|integer|in:301,302',
'single_use' => 'nullable|boolean',
'forward_query_params' => 'nullable|boolean',
'max_visits' => 'nullable|integer|min:1',
'expiration_redirect_url' => 'nullable|url|max:2048',
'activated_at' => 'nullable|date',
'expires_at' => 'nullable|date',
'pixel_meta_id' => 'nullable|string|max:100',
'pixel_google_id' => 'nullable|string|max:100',
'pixel_linkedin_id' => 'nullable|string|max:100',
'webhook_url' => 'nullable|url|max:2048',
]);
$shortUrl = $this->service->create($validated);
// Fire 'created' webhook if active
$this->dispatchCreatedWebhook($shortUrl);
return response()->json([
'message' => 'Short URL created successfully.',
'data' => $this->transformLink($shortUrl),
], 201);
}
/**
* Remove the specified short URL.
*/
public function destroy(int $id): JsonResponse
{
$shortUrl = ShortUrl::findOrFail($id);
$shortUrl->delete();
return response()->json([
'message' => 'Short URL deleted successfully.',
]);
}
/**
* Transform a ShortUrl model to API response array.
*/
private function transformLink(ShortUrl $link): array
{
return [
'id' => $link->id,
'destination_url' => $link->destination_url,
'url_key' => $link->url_key,
'short_url' => $link->getShortUrl(),
'is_enabled' => (bool) $link->is_enabled,
'redirect_status_code' => (int) $link->redirect_status_code,
'total_visits' => (int) $link->total_visits,
'unique_visits' => (int) $link->unique_visits,
'max_visits' => $link->max_visits ? (int) $link->max_visits : null,
'activated_at' => $link->activated_at ? $link->activated_at->toIso8601String() : null,
'expires_at' => $link->expires_at ? $link->expires_at->toIso8601String() : null,
'pixel_meta_id' => $link->pixel_meta_id,
'pixel_google_id' => $link->pixel_google_id,
'pixel_linkedin_id' => $link->pixel_linkedin_id,
'webhook_url' => $link->webhook_url,
'notes' => $link->notes,
'created_at' => $link->created_at->toIso8601String(),
];
}
/**
* Dispatch webhook if global or per-link webhook is active for 'created' event.
*/
private function dispatchCreatedWebhook(ShortUrl $shortUrl): void
{
$targetUrl = $shortUrl->webhook_url;
$globalUrl = config('filament-short-url.global_webhook_url');
$events = config('filament-short-url.webhook_events', []);
if (empty($targetUrl) && ! empty($globalUrl) && in_array('created', $events)) {
$targetUrl = $globalUrl;
}
if (! empty($targetUrl)) {
try {
$connection = config('filament-short-url.queue_connection', 'sync');
dispatch(new SendWebhookJob(
url: $targetUrl,
event: 'created',
payload: [
'event' => 'created',
'timestamp' => now()->toIso8601String(),
'short_url' => $this->transformLink($shortUrl),
]
)->onConnection($connection ?: 'sync'));
} catch (\Throwable $e) {
Log::error('[FilamentShortUrl] Created webhook dispatch failed', [
'url_key' => $shortUrl->url_key,
'error' => $e->getMessage(),
]);
}
}
}
}

View File

@@ -6,9 +6,12 @@ use Bjanczak\FilamentShortUrl\Jobs\TrackShortUrlVisitJob;
use Bjanczak\FilamentShortUrl\Models\ShortUrl;
use Bjanczak\FilamentShortUrl\Services\ClientIpExtractor;
use Bjanczak\FilamentShortUrl\Services\ShortUrlService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\MessageBag;
use Symfony\Component\HttpFoundation\Response;
class ShortUrlRedirectController extends Controller
{
@@ -16,7 +19,7 @@ class ShortUrlRedirectController extends Controller
private readonly ShortUrlService $service,
) {}
public function __invoke(Request $request, string $key): RedirectResponse
public function __invoke(Request $request, string $key): Response
{
$shortUrl = ShortUrl::findByKey($key);
@@ -25,28 +28,120 @@ class ShortUrlRedirectController extends Controller
abort(404);
}
// 410 Gone if disabled or expired
// Redirect to custom expiration URL if defined, otherwise 410 Gone if disabled or expired
if (! $shortUrl->isActive()) {
if ($shortUrl->expiration_redirect_url) {
return redirect()->away($shortUrl->expiration_redirect_url, 302);
}
abort(410);
}
if ($shortUrl->track_visits) {
$connection = config('filament-short-url.queue_connection');
// 1. VPN/Proxy & Bot Blocking Check
if (config('filament-short-url.vpn_detection.enabled', false) && config('filament-short-url.vpn_detection.block_action') === 'block_with_403') {
$ipAddress = ClientIpExtractor::getIp($request);
$countryCode = ClientIpExtractor::getCountryCode($request);
$proxyDetector = app(\Bjanczak\FilamentShortUrl\Services\ProxyDetectionService::class);
$detection = $proxyDetector->detect($ipAddress);
if ($detection['is_proxy'] || $detection['is_bot']) {
abort(403, 'Access denied. VPN, Proxy, or automated scraping connection detected.');
}
}
$job = new TrackShortUrlVisitJob(
shortUrl: $shortUrl,
ipAddress: $ipAddress,
userAgent: $request->userAgent() ?? '',
refererUrl: $request->header('Referer'),
countryCode: $countryCode,
);
// 2. Rate Limiting Check
if (config('filament-short-url.rate_limiting.enabled', false)) {
$maxAttempts = (int) config('filament-short-url.rate_limiting.max_attempts', 60);
$decaySeconds = (int) config('filament-short-url.rate_limiting.decay_seconds', 60);
$ipAddress = ClientIpExtractor::getIp($request);
$limiterKey = "short_url_limit:{$key}:".$ipAddress;
if ($connection && $connection !== 'default') {
dispatch($job->onConnection($connection));
} else {
dispatch($job);
if (RateLimiter::tooManyAttempts($limiterKey, $maxAttempts)) {
$retryAfter = RateLimiter::availableIn($limiterKey);
abort(429, 'Too many requests. Please try again in '.$retryAfter.' seconds.', [
'Retry-After' => $retryAfter,
]);
}
RateLimiter::hit($limiterKey, $decaySeconds);
}
// 3. Password Protection Check
if (! empty($shortUrl->password)) {
$sessionKey = "short-url-auth-{$shortUrl->id}";
if (! session()->get($sessionKey)) {
if ($request->isMethod('POST')) {
$submitted = $request->input('password');
if ($submitted === $shortUrl->password) {
session()->put($sessionKey, true);
return redirect()->to($request->fullUrl());
}
$errors = new MessageBag([
'password' => __('filament-short-url::default.password_error') ?? 'Incorrect password.',
]);
return response(view('filament-short-url::password-prompt', ['errors' => $errors]))
->header('Content-Type', 'text/html');
}
return response(view('filament-short-url::password-prompt'))
->header('Content-Type', 'text/html');
}
}
// 4. Resolve Destination URL (evaluating targeting rules)
$destination = $shortUrl->resolveDestinationUrl($request);
// Forward query parameters if configured
if ($shortUrl->forward_query_params) {
$queryParams = $request->query();
// Remove routing/auth parameters so they don't leak to destination
unset($queryParams['confirmed'], $queryParams['password']);
if (! empty($queryParams)) {
$separator = str_contains($destination, '?') ? '&' : '?';
$destination .= $separator.http_build_query($queryParams);
}
}
// 5. Warning / Intermediate Page Check
if ($shortUrl->show_warning_page && ! $request->has('confirmed')) {
return response(view('filament-short-url::warning', ['destinationUrl' => $destination]))
->header('Content-Type', 'text/html');
}
// 6. Track Visit
if ($shortUrl->track_visits) {
try {
$connection = config('filament-short-url.queue_connection', 'sync');
$ipAddress = ClientIpExtractor::getIp($request);
$countryCode = ClientIpExtractor::getCountryCode($request);
$city = ClientIpExtractor::getCity($request);
$job = new TrackShortUrlVisitJob(
shortUrl: $shortUrl,
ipAddress: $ipAddress,
userAgent: $request->userAgent() ?? '',
refererUrl: $request->header('Referer'),
countryCode: $countryCode,
city: $city,
utmSource: $request->query('utm_source'),
utmMedium: $request->query('utm_medium'),
utmCampaign: $request->query('utm_campaign'),
utmTerm: $request->query('utm_term'),
utmContent: $request->query('utm_content'),
);
if ($connection) {
dispatch($job->onConnection($connection));
} else {
dispatch($job->onConnection('sync'));
}
} catch (\Throwable $e) {
// Never let tracking failures block the redirection of the user!
Log::error('[FilamentShortUrl] Redirect tracking failed', [
'url_key' => $key,
'error' => $e->getMessage(),
]);
}
}
@@ -60,10 +155,20 @@ class ShortUrlRedirectController extends Controller
if ($affected === 0) {
abort(410);
}
// Manually forget cache since DB-level update does not trigger Eloquent events
cache()->forget("filament-short-url:{$shortUrl->url_key}");
}
$redirectUrl = $this->service->resolveRedirectUrl($shortUrl, $request);
if (! empty($shortUrl->pixel_meta_id) || ! empty($shortUrl->pixel_google_id) || ! empty($shortUrl->pixel_linkedin_id)) {
return response(view('filament-short-url::pixel-loading', [
'destination' => $destination,
'pixelMetaId' => $shortUrl->pixel_meta_id,
'pixelGoogleId' => $shortUrl->pixel_google_id,
'pixelLinkedinId' => $shortUrl->pixel_linkedin_id,
]))->header('Content-Type', 'text/html');
}
return redirect()->away($redirectUrl, $shortUrl->redirect_status_code);
return redirect()->away($destination, $shortUrl->redirect_status_code);
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace Bjanczak\FilamentShortUrl\Http\Middleware;
use Bjanczak\FilamentShortUrl\Services\ShortUrlSettingsManager;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AuthenticateShortUrlApi
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next): Response
{
if (! config('filament-short-url.api_enabled', false)) {
return response()->json([
'error' => 'The Developer API is currently disabled. Enable it in Short URL Settings → API & Webhooks.',
], 503);
}
$apiKey = $request->header('X-Api-Key');
if (! $apiKey && $auth = $request->header('Authorization')) {
if (str_starts_with(strtolower($auth), 'bearer ')) {
$apiKey = substr($auth, 7);
}
}
if (empty($apiKey)) {
return response()->json([
'error' => 'Unauthorized. API Key is missing.',
], 401);
}
$mgr = app(ShortUrlSettingsManager::class);
$keys = $mgr->get('api_keys', []);
$valid = false;
foreach ($keys as $keyObj) {
if (($keyObj['key'] ?? '') === $apiKey && (bool) ($keyObj['is_active'] ?? false)) {
$valid = true;
break;
}
}
if (! $valid) {
return response()->json([
'error' => 'Unauthorized. Invalid or inactive API Key.',
], 401);
}
return $next($request);
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace Bjanczak\FilamentShortUrl\Jobs;
use Bjanczak\FilamentShortUrl\Models\ShortUrl;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
class IncrementVisitJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
public function __construct(
public readonly int $shortUrlId,
public readonly bool $isUnique = false,
) {
$this->onQueue(config('filament-short-url.queue_name', 'default'));
}
public function handle(): void
{
$shortUrl = ShortUrl::find($this->shortUrlId);
if (! $shortUrl) {
return;
}
$shortUrl->newQuery()
->where('id', $shortUrl->id)
->increment(
'total_visits',
1,
$this->isUnique ? ['unique_visits' => DB::raw('unique_visits + 1')] : []
);
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace Bjanczak\FilamentShortUrl\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class SendWebhookJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/** @var int Max retry attempts if the webhook fails */
public int $tries = 3;
/** @var int Delay between retries (seconds) */
public int $backoff = 10;
/**
* Create a new job instance.
*/
public function __construct(
public readonly string $url,
public readonly string $event,
public readonly array $payload
) {
$this->onQueue(config('filament-short-url.queue_name', 'default'));
}
/**
* Execute the job.
*/
public function handle(): void
{
try {
$response = Http::timeout(10)
->withHeaders([
'Content-Type' => 'application/json',
'User-Agent' => 'wYachts-ShortUrl-Webhook/1.5',
])
->post($this->url, $this->payload);
if ($response->failed()) {
Log::warning('[FilamentShortUrl] Webhook delivery returned client/server error', [
'url' => $this->url,
'event' => $this->event,
'status' => $response->status(),
]);
// Throw exception to trigger queue retry
throw new \RuntimeException('Webhook failed with status '.$response->status());
}
} catch (\Throwable $e) {
Log::warning('[FilamentShortUrl] Webhook delivery failed', [
'url' => $this->url,
'event' => $this->event,
'error' => $e->getMessage(),
]);
throw $e;
}
}
}

View File

@@ -41,6 +41,12 @@ class TrackShortUrlVisitJob implements ShouldQueue
public readonly string $userAgent,
public readonly ?string $refererUrl,
public readonly ?string $countryCode = null,
public readonly ?string $city = null,
public readonly ?string $utmSource = null,
public readonly ?string $utmMedium = null,
public readonly ?string $utmCampaign = null,
public readonly ?string $utmTerm = null,
public readonly ?string $utmContent = null,
) {
$this->onQueue(config('filament-short-url.queue_name', 'default'));
}
@@ -62,7 +68,19 @@ class TrackShortUrlVisitJob implements ShouldQueue
]);
$countryCode = isset($this->countryCode) ? $this->countryCode : null;
$visit = $tracker->record($shortUrl, $request, $countryCode);
$city = isset($this->city) ? $this->city : null;
$visit = $tracker->record(
shortUrl: $shortUrl,
request: $request,
preResolvedCountryCode: $countryCode,
preResolvedCity: $city,
utmSource: $this->utmSource,
utmMedium: $this->utmMedium,
utmCampaign: $this->utmCampaign,
utmTerm: $this->utmTerm,
utmContent: $this->utmContent,
);
// Null means bot/crawler — nothing to dispatch or report
if ($visit === null) {
@@ -72,6 +90,60 @@ class TrackShortUrlVisitJob implements ShouldQueue
// Fire event for user listeners
ShortUrlVisited::dispatch($shortUrl, $visit);
// Trigger Webhook if active
$targetUrl = $shortUrl->webhook_url;
$globalUrl = config('filament-short-url.global_webhook_url');
$events = config('filament-short-url.webhook_events', []);
if (empty($targetUrl) && ! empty($globalUrl) && in_array('visited', $events)) {
$targetUrl = $globalUrl;
}
if (! empty($targetUrl)) {
try {
dispatch(new SendWebhookJob(
url: $targetUrl,
event: 'visited',
payload: [
'event' => 'visited',
'timestamp' => now()->toIso8601String(),
'short_url' => [
'id' => $shortUrl->id,
'destination_url' => $shortUrl->destination_url,
'url_key' => $shortUrl->url_key,
'short_url' => $shortUrl->getShortUrl(),
'total_visits' => (int) $shortUrl->getRealTimeTotalVisits(),
'unique_visits' => (int) $shortUrl->unique_visits,
],
'visit' => [
'id' => $visit->id,
'visited_at' => $visit->visited_at->toIso8601String(),
'device_type' => $visit->device_type,
'browser' => $visit->browser,
'browser_version' => $visit->browser_version,
'operating_system' => $visit->operating_system,
'operating_system_version' => $visit->operating_system_version,
'country' => $visit->country,
'country_code' => $visit->country_code,
'city' => $visit->city,
'referer_url' => $visit->referer_url,
'referer_host' => $visit->referer_host,
'utm_source' => $visit->utm_source,
'utm_medium' => $visit->utm_medium,
'utm_campaign' => $visit->utm_campaign,
'utm_term' => $visit->utm_term,
'utm_content' => $visit->utm_content,
],
]
)->onConnection($this->connection ?: 'sync'));
} catch (\Throwable $e) {
Log::error('[FilamentShortUrl] Visited webhook dispatch failed', [
'url_key' => $shortUrl->url_key,
'error' => $e->getMessage(),
]);
}
}
// Optional GA4 Measurement Protocol integration
if ($shortUrl->ga_tracking_id && config('filament-short-url.ga4.api_secret')) {
$this->sendGa4Hit($shortUrl, $visit);

View File

@@ -2,15 +2,22 @@
namespace Bjanczak\FilamentShortUrl\Models;
use Bjanczak\FilamentShortUrl\Filament\Resources\ShortUrlResource\Widgets\ShortUrlGlobalOverview;
use Bjanczak\FilamentShortUrl\Jobs\IncrementVisitJob;
use Bjanczak\FilamentShortUrl\Services\ClientIpExtractor;
use Bjanczak\FilamentShortUrl\Services\GeoIpService;
use Bjanczak\FilamentShortUrl\Services\ShortUrlBuilder;
use Bjanczak\FilamentShortUrl\Services\ShortUrlService;
use Bjanczak\FilamentShortUrl\Services\UserAgentParser;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
/**
* @property int $id
@@ -66,8 +73,17 @@ class ShortUrl extends Model
'track_referer_url',
'qr_options',
'ga_tracking_id',
'password',
'show_warning_page',
'targeting_rules',
'total_visits',
'unique_visits',
'max_visits',
'expiration_redirect_url',
'pixel_meta_id',
'pixel_google_id',
'pixel_linkedin_id',
'webhook_url',
];
/** @var array<string, string> */
@@ -84,6 +100,9 @@ class ShortUrl extends Model
'track_device_type' => 'boolean',
'track_referer_url' => 'boolean',
'qr_options' => 'array',
'show_warning_page' => 'boolean',
'targeting_rules' => 'array',
'max_visits' => 'integer',
'activated_at' => 'datetime',
'deactivated_at' => 'datetime',
'expires_at' => 'datetime',
@@ -96,6 +115,11 @@ class ShortUrl extends Model
return $this->hasMany(ShortUrlVisit::class, 'short_url_id');
}
public function dailyStats(): HasMany
{
return $this->hasMany(ShortUrlDailyStats::class, 'short_url_id');
}
// ─── Scopes ──────────────────────────────────────────────────────────────
public function scopeEnabled(Builder $query): Builder
@@ -107,9 +131,21 @@ class ShortUrl extends Model
{
return $query
->enabled()
->where(fn (Builder $q) => $q
->whereNull('activated_at')
->orWhere('activated_at', '<=', now())
)
->where(fn (Builder $q) => $q
->whereNull('deactivated_at')
->orWhere('deactivated_at', '>', now())
)
->where(fn (Builder $q) => $q
->whereNull('expires_at')
->orWhere('expires_at', '>', now())
)
->where(fn (Builder $q) => $q
->whereNull('max_visits')
->orWhereRaw('total_visits < max_visits')
);
}
@@ -140,12 +176,50 @@ class ShortUrl extends Model
}
/**
* Bust the cache when the model is saved or deleted.
* Bust the redirect cache when the model is saved or deleted.
* Also invalidate the global overview link-count cache (forever cache)
* on creation or deletion — the count changes only in those cases.
*/
protected static function booted(): void
{
static::saved(fn (self $m) => cache()->forget("filament-short-url:{$m->url_key}"));
static::saving(function (self $m) {
if ($m->single_use) {
$m->max_visits = null;
}
if ($m->activated_at === null && $m->expires_at === null) {
$m->expiration_redirect_url = null;
}
if (empty($m->pixel_meta_id)) {
$m->pixel_meta_id = null;
}
if (empty($m->pixel_google_id)) {
$m->pixel_google_id = null;
}
if (empty($m->pixel_linkedin_id)) {
$m->pixel_linkedin_id = null;
}
if (empty($m->webhook_url)) {
$m->webhook_url = null;
}
});
static::saved(function (self $m) {
cache()->forget("filament-short-url:{$m->url_key}");
if ($m->wasChanged('url_key')) {
$oldKey = $m->getOriginal('url_key');
if ($oldKey) {
cache()->forget("filament-short-url:{$oldKey}");
}
}
});
static::deleted(fn (self $m) => cache()->forget("filament-short-url:{$m->url_key}"));
// Bust the forever-cached link counts displayed in the global overview widget.
static::created(fn () => cache()->forget(ShortUrlGlobalOverview::LINKS_CACHE_KEY));
static::deleted(fn () => cache()->forget(ShortUrlGlobalOverview::LINKS_CACHE_KEY));
}
/** @return Collection<int, static> */
@@ -164,7 +238,17 @@ class ShortUrl extends Model
return app(ShortUrlService::class)->destination($url);
}
// ─── Helpers ─────────────────────────────────────────────────────────────
public function getRealTimeTotalVisits(): int
{
$total = $this->total_visits;
if (config('filament-short-url.counter_buffering.enabled', false)) {
$prefix = config('filament-short-url.counter_buffering.cache_key_prefix', 'filament-short-url:buffer:');
$total += (int) cache()->get("{$prefix}total:{$this->id}", 0);
}
return $total;
}
public function isActive(): bool
{
@@ -187,12 +271,25 @@ class ShortUrl extends Model
return false;
}
// Visit limit reached
if (! $this->single_use && $this->max_visits !== null && $this->getRealTimeTotalVisits() >= $this->max_visits) {
return false;
}
return true;
}
public function isExpired(): bool
{
return $this->expires_at !== null && $this->expires_at->isPast();
if ($this->expires_at !== null && $this->expires_at->isPast()) {
return true;
}
if (! $this->single_use && $this->max_visits !== null && $this->getRealTimeTotalVisits() >= $this->max_visits) {
return true;
}
return false;
}
public function trackingEnabled(): bool
@@ -236,12 +333,103 @@ class ShortUrl extends Model
return rtrim(config('app.url'), '/')."/{$prefix}/{$this->url_key}";
}
/**
* Resolve the targeted destination URL based on request headers/context.
*/
public function resolveDestinationUrl(Request $request): string
{
$rules = $this->targeting_rules;
if (empty($rules)) {
return $this->destination_url;
}
$type = $rules['type'] ?? 'none';
if ($type === 'device') {
$parser = app(UserAgentParser::class);
$deviceType = $parser->parse($request->userAgent() ?? '')['device_type'];
if ($deviceType === 'mobile') {
return $rules['device']['mobile'] ?? $rules['device']['ios'] ?? $this->destination_url;
}
if ($deviceType === 'tablet') {
return $rules['device']['tablet'] ?? $rules['device']['android'] ?? $this->destination_url;
}
return $rules['device']['desktop'] ?? $this->destination_url;
}
if ($type === 'geo') {
$countryCode = ClientIpExtractor::getCountryCode($request);
if (! $countryCode) {
// Try resolving via GeoIpService
$ip = ClientIpExtractor::getIp($request);
$geo = app(GeoIpService::class)->resolve($ip);
$countryCode = $geo['country_code'] ?? null;
}
if ($countryCode) {
$countryCode = strtoupper(trim($countryCode));
foreach ($rules['geo'] ?? [] as $rule) {
if (strtoupper($rule['country_code'] ?? '') === $countryCode) {
return $rule['url'] ?? $this->destination_url;
}
}
}
}
if ($type === 'rotation') {
$items = $rules['rotation'] ?? [];
if (! empty($items)) {
$totalWeight = array_sum(array_column($items, 'weight'));
if ($totalWeight > 0) {
$rand = mt_rand(1, $totalWeight);
$currentWeight = 0;
foreach ($items as $item) {
$currentWeight += (int) ($item['weight'] ?? 0);
if ($rand <= $currentWeight) {
return $item['url'] ?? $this->destination_url;
}
}
}
}
}
return $this->destination_url;
}
/**
* Atomically increment visit counters — single query when unique,
* to avoid race conditions and two round-trips.
* to avoid race conditions and two round-trips. Supports write-back caching.
*/
public function incrementVisits(bool $isUnique = false): void
{
if (config('filament-short-url.counter_buffering.enabled', false)) {
if (cache()->getDefaultDriver() === 'redis' && class_exists(Redis::class)) {
$prefix = config('filament-short-url.counter_buffering.cache_key_prefix', 'filament-short-url:buffer:');
try {
cache()->increment("{$prefix}total:{$this->id}");
if ($isUnique) {
cache()->increment("{$prefix}unique:{$this->id}");
}
Redis::sadd("{$prefix}dirty_ids", $this->id);
return;
} catch (\Throwable) {
// Fallback to queue job below
}
}
// Safe fallback: Dispatch async job so clicks are queued and not lost on cache clear
$connection = config('filament-short-url.queue_connection', 'sync');
dispatch(new IncrementVisitJob($this->id, $isUnique)->onConnection($connection ?: 'sync'));
return;
}
$this->newQuery()
->where('id', $this->id)
->increment('total_visits', 1, $isUnique ? ['unique_visits' => DB::raw('unique_visits + 1')] : []);
@@ -252,98 +440,304 @@ class ShortUrl extends Model
*
* @return array<string, mixed>
*/
public function getCachedStats(): array
public function getCachedStats(?string $dateFrom = null, ?string $dateTo = null): array
{
$dateFromClean = $dateFrom ? Carbon::parse($dateFrom)->toDateString() : null;
$dateToClean = $dateTo ? Carbon::parse($dateTo)->toDateString() : null;
$cacheTtl = (int) config('filament-short-url.geo_ip.stats_cache_ttl', 300);
$cacheKey = "short_url_stats_{$this->id}";
$cacheKey = "short_url_stats_{$this->id}_".($dateFromClean ?: 'all').'_'.($dateToClean ?: 'all');
return cache()->remember($cacheKey, $cacheTtl, function () {
$visits = $this->visits();
return cache()->remember($cacheKey, $cacheTtl, function () use ($dateFromClean, $dateToClean) {
$today = Carbon::today()->toDateString();
$totalVisits = (int) ($this->total_visits ?? 0);
$uniqueVisits = (int) ($this->unique_visits ?? 0);
$visitsToday = (clone $visits)->where('visited_at', '>=', today()->startOfDay())->count();
$visitsThisWeek = (clone $visits)->where('visited_at', '>=', now()->startOfWeek())->count();
$visitsThisMonth = (clone $visits)->where('visited_at', '>=', now()->startOfMonth())->count();
// 1. Fetch daily stats (aggregated historical data)
$dailyQuery = $this->dailyStats()->where('date', '<', $today);
if ($dateFromClean) {
$dailyQuery->where('date', '>=', $dateFromClean);
}
if ($dateToClean && $dateToClean < $today) {
$dailyQuery->where('date', '<=', $dateToClean);
}
$dailyStatsRows = $dailyQuery->get();
// Visits by day — last 30 days
$visitsByDayRaw = (clone $visits)
->where('visited_at', '>=', now()->subDays(29)->startOfDay())
->selectRaw('DATE(visited_at) as date, COUNT(*) as count')
->groupBy('date')
->orderBy('date')
->pluck('count', 'date')
->toArray();
$visitsByDay = [];
for ($i = 29; $i >= 0; $i--) {
$date = now()->subDays($i)->format('Y-m-d');
$visitsByDay[$date] = $visitsByDayRaw[$date] ?? 0;
// 2. Fetch raw visits for today (if within date range)
$includeToday = ($dateToClean === null || $dateToClean >= $today);
if ($dateFromClean && $dateFromClean > $today) {
$includeToday = false;
}
// Top countries
$visitsByCountry = (clone $visits)
->whereNotNull('country')
->selectRaw('country, country_code, COUNT(*) as count')
->groupBy('country', 'country_code')
->orderByDesc('count')
->limit(10)
->get()
->mapWithKeys(fn ($row) => [$row->country => $row->count])
->toArray();
$rawVisits = [];
if ($includeToday) {
$rawVisits = $this->visits()->where('visited_at', '>=', $today.' 00:00:00')->get();
}
// Device types
$visitsByDevice = (clone $visits)
->whereNotNull('device_type')
->selectRaw('device_type, COUNT(*) as count')
->groupBy('device_type')
->orderByDesc('count')
->pluck('count', 'device_type')
->toArray();
// Helper to merge associative stats arrays
$mergeStats = function (array $base, ?array $additional): array {
if (empty($additional)) {
return $base;
}
foreach ($additional as $key => $val) {
$base[$key] = ($base[$key] ?? 0) + $val;
}
// Browsers
$visitsByBrowser = (clone $visits)
->whereNotNull('browser')
->selectRaw('browser, COUNT(*) as count')
->groupBy('browser')
->orderByDesc('count')
->limit(8)
->pluck('count', 'browser')
->toArray();
return $base;
};
// Operating systems
$visitsByOs = (clone $visits)
->whereNotNull('operating_system')
->selectRaw('operating_system, COUNT(*) as count')
->groupBy('operating_system')
->orderByDesc('count')
->limit(8)
->pluck('count', 'operating_system')
->toArray();
// Initialize metrics
$totalVisits = 0;
$uniqueVisitsCount = 0;
$visitsToday = count($rawVisits);
$visitsThisWeek = 0;
$visitsThisMonth = 0;
// Top referers
$visitsByReferer = (clone $visits)
->whereNotNull('referer_url')
->selectRaw('referer_url, COUNT(*) as count')
->groupBy('referer_url')
->orderByDesc('count')
->limit(10)
->pluck('count', 'referer_url')
->toArray();
$visitsByCountry = [];
$visitsByCity = [];
$visitsByDevice = [];
$visitsByBrowser = [];
$visitsByOs = [];
$visitsByReferer = [];
$utmSources = [];
$utmMediums = [];
$utmCampaigns = [];
// Sum up daily stats
$startOfWeek = now()->startOfWeek()->toDateString();
$startOfMonth = now()->startOfMonth()->toDateString();
foreach ($dailyStatsRows as $row) {
$totalVisits += $row->visits_count;
$uniqueVisitsCount += $row->unique_visits_count;
$rowDate = $row->date->toDateString();
if ($rowDate >= $startOfWeek) {
$visitsThisWeek += $row->visits_count;
}
if ($rowDate >= $startOfMonth) {
$visitsThisMonth += $row->visits_count;
}
$visitsByCountry = $mergeStats($visitsByCountry, $row->country_stats);
$visitsByCity = $mergeStats($visitsByCity, $row->city_stats);
$visitsByDevice = $mergeStats($visitsByDevice, $row->device_stats);
$visitsByBrowser = $mergeStats($visitsByBrowser, $row->browser_stats);
$visitsByOs = $mergeStats($visitsByOs, $row->os_stats);
$visitsByReferer = $mergeStats($visitsByReferer, $row->referer_stats);
$utmSources = $mergeStats($utmSources, $row->utm_source_stats);
$utmMediums = $mergeStats($utmMediums, $row->utm_medium_stats);
$utmCampaigns = $mergeStats($utmCampaigns, $row->utm_campaign_stats);
}
// Combine today's raw visits
if ($includeToday) {
$totalVisits += count($rawVisits);
$uniqueVisitsCount += count(array_unique(array_filter($rawVisits->pluck('ip_hash')->toArray())));
$visitsThisWeek += count($rawVisits);
$visitsThisMonth += count($rawVisits);
foreach ($rawVisits as $visit) {
if ($visit->country) {
$visitsByCountry[$visit->country] = ($visitsByCountry[$visit->country] ?? 0) + 1;
}
if ($visit->city) {
$cityKey = "{$visit->city} ({$visit->country_code})";
$visitsByCity[$cityKey] = ($visitsByCity[$cityKey] ?? 0) + 1;
}
if ($visit->device_type) {
$visitsByDevice[$visit->device_type] = ($visitsByDevice[$visit->device_type] ?? 0) + 1;
}
if ($visit->browser) {
$visitsByBrowser[$visit->browser] = ($visitsByBrowser[$visit->browser] ?? 0) + 1;
}
if ($visit->operating_system) {
$visitsByOs[$visit->operating_system] = ($visitsByOs[$visit->operating_system] ?? 0) + 1;
}
$refererHost = $visit->referer_host ?: 'Direct';
$visitsByReferer[$refererHost] = ($visitsByReferer[$refererHost] ?? 0) + 1;
if ($visit->utm_source) {
$utmSources[$visit->utm_source] = ($utmSources[$visit->utm_source] ?? 0) + 1;
}
if ($visit->utm_medium) {
$utmMediums[$visit->utm_medium] = ($utmMediums[$visit->utm_medium] ?? 0) + 1;
}
if ($visit->utm_campaign) {
$utmCampaigns[$visit->utm_campaign] = ($utmCampaigns[$visit->utm_campaign] ?? 0) + 1;
}
}
}
// Build visitsByDay timeline
$chartFrom = $dateFromClean ? Carbon::parse($dateFromClean) : now()->subDays(29)->startOfDay();
$chartTo = $dateToClean ? Carbon::parse($dateToClean) : now()->endOfDay();
$daysDiff = (int) $chartFrom->diffInDays($chartTo);
$visitsByDay = [];
if ($daysDiff > 90) {
// Group by month
foreach ($dailyStatsRows as $row) {
$m = $row->date->format('Y-m');
$visitsByDay[$m] = ($visitsByDay[$m] ?? 0) + $row->visits_count;
}
if ($includeToday) {
$mToday = Carbon::parse($today)->format('Y-m');
$visitsByDay[$mToday] = ($visitsByDay[$mToday] ?? 0) + count($rawVisits);
}
} else {
// Initialize timeline with zeros
for ($i = $daysDiff; $i >= 0; $i--) {
$d = (clone $chartTo)->subDays($i)->format('Y-m-d');
$visitsByDay[$d] = 0;
}
// Fill daily stats
foreach ($dailyStatsRows as $row) {
$d = $row->date->format('Y-m-d');
if (isset($visitsByDay[$d])) {
$visitsByDay[$d] = $row->visits_count;
}
}
// Fill today
if ($includeToday && isset($visitsByDay[$today])) {
$visitsByDay[$today] = count($rawVisits);
}
}
// Sort distributions descending
arsort($visitsByCountry);
arsort($visitsByCity);
arsort($visitsByDevice);
arsort($visitsByBrowser);
arsort($visitsByOs);
arsort($visitsByReferer);
arsort($utmSources);
arsort($utmMediums);
arsort($utmCampaigns);
return [
'totalVisits' => $totalVisits,
'uniqueVisits' => $uniqueVisits,
'uniqueVisits' => $uniqueVisitsCount,
'visitsToday' => $visitsToday,
'visitsThisWeek' => $visitsThisWeek,
'visitsThisMonth' => $visitsThisMonth,
'visitsByDay' => $visitsByDay,
'visitsByCountry' => $visitsByCountry,
'visitsByCountry' => array_slice($visitsByCountry, 0, 10, true),
'visitsByCity' => array_slice($visitsByCity, 0, 10, true),
'visitsByDevice' => $visitsByDevice,
'visitsByBrowser' => $visitsByBrowser,
'visitsByOs' => $visitsByOs,
'visitsByReferer' => $visitsByReferer,
'visitsByBrowser' => array_slice($visitsByBrowser, 0, 8, true),
'visitsByOs' => array_slice($visitsByOs, 0, 8, true),
'visitsByReferer' => array_slice($visitsByReferer, 0, 10, true),
'utmSources' => array_slice($utmSources, 0, 8, true),
'utmMediums' => array_slice($utmMediums, 0, 8, true),
'utmCampaigns' => array_slice($utmCampaigns, 0, 8, true),
];
});
}
/**
* Cache properties to hold preloaded buffered visits for the current request.
*/
protected static ?array $bufferedTotalVisits = null;
protected static ?array $bufferedUniqueVisits = null;
/**
* Preload all buffered clicks in a single batch query for the entire request.
* Prevents N+1 database queries even if database cache driver is used.
*/
protected static function loadAllBufferedVisits(): void
{
if (static::$bufferedTotalVisits !== null) {
return;
}
static::$bufferedTotalVisits = [];
static::$bufferedUniqueVisits = [];
if (! config('filament-short-url.counter_buffering.enabled', false)) {
return;
}
$prefix = config('filament-short-url.counter_buffering.cache_key_prefix', 'filament-short-url:buffer:');
$dirtyKey = "{$prefix}dirty_ids";
// 1. Fetch the list of dirty IDs (URLs with pending buffered clicks) in one query
$dirtyIds = [];
try {
if (cache()->getDefaultDriver() === 'redis' && class_exists(Redis::class)) {
$dirtyIds = Redis::smembers($dirtyKey);
} else {
$dirtyIds = cache()->get($dirtyKey, []);
}
} catch (\Throwable) {
// Fallback
}
if (empty($dirtyIds)) {
return;
}
$dirtyIds = array_unique(array_filter((array) $dirtyIds));
// 2. Build array of keys to fetch in a single cache store read
$totalKeys = [];
$uniqueKeys = [];
foreach ($dirtyIds as $id) {
$totalKeys[$id] = "{$prefix}total:{$id}";
$uniqueKeys[$id] = "{$prefix}unique:{$id}";
}
try {
// Cache::many() is highly optimized (e.g. 1 database query for database store, or 1 MGET for Redis)
$totals = cache()->many(array_values($totalKeys));
$uniques = cache()->many(array_values($uniqueKeys));
foreach ($totalKeys as $id => $key) {
static::$bufferedTotalVisits[$id] = (int) ($totals[$key] ?? 0);
}
foreach ($uniqueKeys as $id => $key) {
static::$bufferedUniqueVisits[$id] = (int) ($uniques[$key] ?? 0);
}
} catch (\Throwable) {
// Fallback
}
}
/**
* Get the total visits count, merging the database value with any buffered clicks in cache.
* Prevents database N+1 queries.
*/
public function getTotalVisitsAttribute(): int
{
$dbValue = $this->attributes['total_visits'] ?? 0;
if (! config('filament-short-url.counter_buffering.enabled', false)) {
return $dbValue;
}
static::loadAllBufferedVisits();
$buffered = static::$bufferedTotalVisits[$this->id] ?? 0;
return $dbValue + $buffered;
}
/**
* Get the unique visits count, merging the database value with any buffered clicks in cache.
* Prevents database N+1 queries.
*/
public function getUniqueVisitsAttribute(): int
{
$dbValue = $this->attributes['unique_visits'] ?? 0;
if (! config('filament-short-url.counter_buffering.enabled', false)) {
return $dbValue;
}
static::loadAllBufferedVisits();
$buffered = static::$bufferedUniqueVisits[$this->id] ?? 0;
return $dbValue + $buffered;
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Bjanczak\FilamentShortUrl\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
/**
* @property int $id
* @property int $short_url_id
* @property Carbon $date
* @property int $visits_count
* @property int $unique_visits_count
* @property array|null $device_stats
* @property array|null $browser_stats
* @property array|null $os_stats
* @property array|null $country_stats
* @property array|null $city_stats
* @property array|null $referer_stats
* @property array|null $utm_source_stats
* @property array|null $utm_medium_stats
* @property array|null $utm_campaign_stats
* @property Carbon $created_at
* @property Carbon $updated_at
*/
class ShortUrlDailyStats extends Model
{
protected $table = 'short_url_daily_stats';
protected $fillable = [
'short_url_id',
'date',
'visits_count',
'unique_visits_count',
'device_stats',
'browser_stats',
'os_stats',
'country_stats',
'city_stats',
'referer_stats',
'utm_source_stats',
'utm_medium_stats',
'utm_campaign_stats',
];
/** @var array<string, string> */
protected $casts = [
'date' => 'date',
'visits_count' => 'integer',
'unique_visits_count' => 'integer',
'device_stats' => 'array',
'browser_stats' => 'array',
'os_stats' => 'array',
'country_stats' => 'array',
'city_stats' => 'array',
'referer_stats' => 'array',
'utm_source_stats' => 'array',
'utm_medium_stats' => 'array',
'utm_campaign_stats' => 'array',
];
public function shortUrl(): BelongsTo
{
return $this->belongsTo(ShortUrl::class, 'short_url_id');
}
}

View File

@@ -37,14 +37,25 @@ class ShortUrlVisit extends Model
'operating_system_version',
'device_type',
'referer_url',
'referer_host',
'country',
'country_code',
'city',
'utm_source',
'utm_medium',
'utm_campaign',
'utm_term',
'utm_content',
'visited_at',
'is_bot',
'is_proxy',
];
/** @var array<string, string> */
protected $casts = [
'visited_at' => 'datetime',
'is_bot' => 'boolean',
'is_proxy' => 'boolean',
];
public function shortUrl(): BelongsTo

View File

@@ -11,29 +11,31 @@ class ClientIpExtractor
*/
public static function getIp(Request $request): string
{
// 1. Cloudflare connecting IP header
if ($cfIp = $request->header('CF-Connecting-IP')) {
return trim($cfIp);
if (config('filament-short-url.trust_cdn_headers', false)) {
// 1. Cloudflare connecting IP header
if ($cfIp = $request->header('CF-Connecting-IP')) {
return trim($cfIp);
}
// 2. Akamai or other CDNs True-Client-IP header
if ($trueIp = $request->header('True-Client-IP')) {
return trim($trueIp);
}
// 3. General reverse proxy / Nginx X-Real-IP header
if ($realIp = $request->header('X-Real-IP')) {
return trim($realIp);
}
// 4. Standard X-Forwarded-For header chain (first IP is the client)
if ($forwardedFor = $request->header('X-Forwarded-For')) {
$ips = explode(',', $forwardedFor);
return trim($ips[0]);
}
}
// 2. Akamai or other CDNs True-Client-IP header
if ($trueIp = $request->header('True-Client-IP')) {
return trim($trueIp);
}
// 3. General reverse proxy / Nginx X-Real-IP header
if ($realIp = $request->header('X-Real-IP')) {
return trim($realIp);
}
// 4. Standard X-Forwarded-For header chain (first IP is the client)
if ($forwardedFor = $request->header('X-Forwarded-For')) {
$ips = explode(',', $forwardedFor);
return trim($ips[0]);
}
// 5. Fallback to standard Laravel/Symfony IP resolver
// 5. Fallback to standard Laravel/Symfony IP resolver (which respects Trusted Proxies)
return $request->ip() ?? '0.0.0.0';
}
@@ -42,19 +44,39 @@ class ClientIpExtractor
*/
public static function getCountryCode(Request $request): ?string
{
// 1. Cloudflare IP Country header
if ($cfCountry = $request->header('CF-IPCountry')) {
return strtoupper(trim($cfCountry));
if (config('filament-short-url.trust_cdn_headers', false)) {
// 1. Cloudflare IP Country header
if ($cfCountry = $request->header('CF-IPCountry')) {
return strtoupper(trim($cfCountry));
}
// 2. AWS CloudFront country header
if ($cfViewerCountry = $request->header('CloudFront-Viewer-Country')) {
return strtoupper(trim($cfViewerCountry));
}
// 3. Generic CDN / Proxy country header
if ($xCountry = $request->header('X-Country-Code')) {
return strtoupper(trim($xCountry));
}
}
// 2. AWS CloudFront country header
if ($cfViewerCountry = $request->header('CloudFront-Viewer-Country')) {
return strtoupper(trim($cfViewerCountry));
}
return null;
}
// 3. Generic CDN / Proxy country header
if ($xCountry = $request->header('X-Country-Code')) {
return strtoupper(trim($xCountry));
/**
* Extract the edge-provided city name from CDN/proxy headers.
*/
public static function getCity(Request $request): ?string
{
if (config('filament-short-url.trust_cdn_headers', false)) {
if ($cfCity = $request->header('CF-IPCity')) {
return trim($cfCity);
}
if ($cfViewerCity = $request->header('CloudFront-Viewer-City')) {
return trim($cfViewerCity);
}
}
return null;

View File

@@ -17,31 +17,32 @@ use Illuminate\Support\Facades\Log;
*/
class GeoIpService
{
private const API_URL = 'http://ip-api.com/json/%s?fields=status,country,countryCode';
private const API_URL = 'http://ip-api.com/json/%s?fields=status,country,countryCode,city';
/** @var array<string, array{country: string|null, country_code: string|null}> */
/** @var array<string, array{country: string|null, country_code: string|null, city: string|null}> */
private static array $runtimeCache = [];
/**
* Resolve country data for the given IP address.
* Resolve country and city data for the given IP address.
*
* @return array{country: string|null, country_code: string|null}
* @return array{country: string|null, country_code: string|null, city: string|null}
*/
public function resolve(string $ip, ?string $preResolvedCountryCode = null): array
public function resolve(string $ip, ?string $preResolvedCountryCode = null, ?string $preResolvedCity = null): array
{
$empty = ['country' => null, 'country_code' => null];
$empty = ['country' => null, 'country_code' => null, 'city' => null];
if (! config('filament-short-url.geo_ip.enabled', true)) {
return $empty;
}
// 1. Prioritise edge-provided CDN country code (extremely fast, zero latency)
// 1. Prioritise edge-provided CDN country code & city (extremely fast, zero latency)
if ($preResolvedCountryCode) {
$code = strtoupper(trim($preResolvedCountryCode));
return [
'country' => $this->getCountryName($code),
'country_code' => $code,
'city' => $preResolvedCity,
];
}
@@ -129,9 +130,9 @@ class GeoIpService
}
/**
* Resolve country using local MaxMind GeoIP2 DB.
* Resolve country and city using local MaxMind GeoIP2 DB.
*
* @return array{country: string, country_code: string}|null
* @return array{country: string|null, country_code: string|null, city: string|null}|null
*/
private function lookupMaxMind(string $ip): ?array
{
@@ -151,11 +152,24 @@ class GeoIpService
try {
$reader = new Reader($dbPath);
$dbType = $reader->metadata()->databaseType;
if (str_contains($dbType, 'City')) {
$record = $reader->city($ip);
return [
'country' => $record->country->name ?? null,
'country_code' => $record->country->isoCode ?? null,
'city' => $record->city->name ?? null,
];
}
$record = $reader->country($ip);
return [
'country' => $record->country->name ?? null,
'country_code' => $record->country->isoCode ?? null,
'city' => null,
];
} catch (\Throwable $e) {
Log::warning('[FilamentShortUrl] MaxMind GeoIP lookup failed', [
@@ -168,9 +182,9 @@ class GeoIpService
}
/**
* Resolve country using free ip-api.com.
* Resolve country and city using free ip-api.com.
*
* @return array{country: string, country_code: string}|null
* @return array{country: string|null, country_code: string|null, city: string|null}|null
*/
private function fetchFromApi(string $ip): ?array
{
@@ -193,6 +207,7 @@ class GeoIpService
return [
'country' => $data['country'] ?? null,
'country_code' => $data['countryCode'] ?? null,
'city' => $data['city'] ?? null,
];
} catch (\Throwable $e) {
Log::warning('[FilamentShortUrl] GeoIP lookup failed', [

View File

@@ -0,0 +1,108 @@
<?php
namespace Bjanczak\FilamentShortUrl\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class ProxyDetectionService
{
/**
* Detect if an IP address belongs to a VPN, proxy, Tor node, or data center hosting.
*
* @return array{is_proxy: bool, is_bot: bool}
*/
public function detect(string $ip): array
{
if (empty($ip) || $ip === '127.0.0.1' || $ip === '::1') {
return ['is_proxy' => false, 'is_bot' => false];
}
$enabled = config('filament-short-url.vpn_detection.enabled', false);
if (! $enabled) {
return ['is_proxy' => false, 'is_bot' => false];
}
$cacheKey = "short-url:proxy-check:{$ip}";
$cacheTtl = (int) config('filament-short-url.vpn_detection.cache_ttl', 86400);
return Cache::remember($cacheKey, $cacheTtl, function () use ($ip) {
$driver = config('filament-short-url.vpn_detection.driver', 'ip-api');
$timeout = (int) config('filament-short-url.vpn_detection.timeout', 2);
try {
if ($driver === 'vpnapi') {
return $this->queryVpnApi($ip, $timeout);
}
// Default to ip-api
return $this->queryIpApi($ip, $timeout);
} catch (\Throwable $e) {
Log::warning("Proxy detection failed for IP: {$ip}. Error: " . $e->getMessage());
return ['is_proxy' => false, 'is_bot' => false];
}
});
}
/**
* Query ip-api.com endpoint.
*
* @return array{is_proxy: bool, is_bot: bool}
*/
private function queryIpApi(string $ip, int $timeout): array
{
$url = "http://ip-api.com/json/{$ip}?fields=status,message,proxy,hosting";
$response = Http::timeout($timeout)->get($url);
if ($response->failed() || $response->json('status') === 'fail') {
return ['is_proxy' => false, 'is_bot' => false];
}
$isProxy = (bool) $response->json('proxy', false);
$isBot = (bool) $response->json('hosting', false); // hosting indicates data centers (bots/scrapers)
return [
'is_proxy' => $isProxy,
'is_bot' => $isBot,
];
}
/**
* Query vpnapi.io endpoint.
*
* @return array{is_proxy: bool, is_bot: bool}
*/
private function queryVpnApi(string $ip, int $timeout): array
{
$key = config('filament-short-url.vpn_detection.vpnapi_key');
if (empty($key)) {
return ['is_proxy' => false, 'is_bot' => false];
}
$url = "https://vpnapi.io/api/{$ip}?key={$key}";
$response = Http::timeout($timeout)->get($url);
if ($response->failed()) {
return ['is_proxy' => false, 'is_bot' => false];
}
$security = $response->json('security', []);
$isVpn = (bool) ($security['vpn'] ?? false);
$isProxy = (bool) ($security['proxy'] ?? false);
$isTor = (bool) ($security['tor'] ?? false);
$isRelay = (bool) ($security['relay'] ?? false);
// Treat hosting/data center as bot traffic
$isHosting = (bool) ($response->json('security.hosting') ?? false);
return [
'is_proxy' => $isVpn || $isProxy || $isTor || $isRelay,
'is_bot' => $isHosting,
];
}
}

View File

@@ -0,0 +1,77 @@
<?php
namespace Bjanczak\FilamentShortUrl\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class SafeBrowsingService
{
/**
* Check if a URL is safe using Google Safe Browsing API.
*
* Returns true if safe (or if API is disabled/failed), false if a threat is detected.
*/
public function isSafe(string $url): bool
{
$enabled = config('filament-short-url.safe_browsing.enabled', false);
$apiKey = config('filament-short-url.safe_browsing.api_key');
if (! $enabled || empty($apiKey)) {
return true;
}
return $this->isSafeWithKey($url, $apiKey);
}
/**
* Check if a URL is safe using Google Safe Browsing API with a specific key.
*/
public function isSafeWithKey(string $url, string $apiKey): bool
{
if (empty($apiKey)) {
return true;
}
try {
$endpoint = "https://safebrowsing.googleapis.com/v4/threatMatches:find?key={$apiKey}";
$payload = [
'client' => [
'clientId' => 'filament-short-url-plugin',
'clientVersion' => '2.0.0',
],
'threatInfo' => [
'threatTypes' => [
'MALWARE',
'SOCIAL_ENGINEERING',
'UNWANTED_SOFTWARE',
'POTENTIALLY_HARMFUL_APPLICATION',
],
'platformTypes' => ['ANY_PLATFORM'],
'threatEntryTypes' => ['URL'],
'threatEntries' => [
['url' => $url],
],
],
];
$response = Http::timeout(3)
->withHeaders(['Content-Type' => 'application/json'])
->post($endpoint, $payload);
if ($response->failed()) {
Log::warning("Google Safe Browsing API request failed with status: " . $response->status());
return true; // Default to safe if API is down
}
$matches = $response->json('matches', []);
// If there are matches, the URL is flagged as unsafe
return empty($matches);
} catch (\Throwable $e) {
Log::warning("Google Safe Browsing check failed: " . $e->getMessage());
return true; // Default to safe on exception
}
}
}

View File

@@ -51,6 +51,34 @@ class ShortUrlBuilder
return $this;
}
public function activatedAt(\DateTimeInterface|Carbon|null $date): static
{
$this->data['activated_at'] = $date ? Carbon::instance($date) : null;
return $this;
}
public function deactivatedAt(\DateTimeInterface|Carbon|null $date): static
{
$this->data['deactivated_at'] = $date ? Carbon::instance($date) : null;
return $this;
}
public function maxVisits(?int $maxVisits): static
{
$this->data['max_visits'] = $maxVisits;
return $this;
}
public function expirationRedirectUrl(?string $url): static
{
$this->data['expiration_redirect_url'] = $url;
return $this;
}
public function trackVisits(bool $track = true): static
{
$this->data['track_visits'] = $track;

View File

@@ -107,13 +107,15 @@ class ShortUrlService
*/
public function resolveRedirectUrl(ShortUrl $shortUrl, Request $request): string
{
$destination = $shortUrl->destination_url;
$destination = $shortUrl->resolveDestinationUrl($request);
if (! $shortUrl->forward_query_params) {
return $destination;
}
$queryParams = $request->query();
// Remove routing/auth parameters so they don't leak to destination
unset($queryParams['confirmed'], $queryParams['password']);
if (empty($queryParams)) {
return $destination;

View File

@@ -2,6 +2,7 @@
namespace Bjanczak\FilamentShortUrl\Services;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
class ShortUrlSettingsManager
@@ -44,11 +45,49 @@ class ShortUrlSettingsManager
'geo_ip_driver' => config('filament-short-url.geo_ip.driver', 'headers'),
'geo_ip_cache_ttl' => config('filament-short-url.geo_ip.cache_ttl', 86400),
'geo_ip_timeout' => config('filament-short-url.geo_ip.timeout', 3),
'maxmind_database_path' => config('filament-short-url.geo_ip.maxmind.database_path', database_path('geoip/GeoLite2-Country.mmdb')),
'maxmind_database_path' => config('filament-short-url.geo_ip.maxmind.database_path', storage_path('geoip/GeoLite2-Country.mmdb')),
'geo_ip_stats_cache_ttl' => config('filament-short-url.geo_ip.stats_cache_ttl', 300),
'ga4_api_secret' => config('filament-short-url.ga4.api_secret'),
'ga4_firebase_app_id' => config('filament-short-url.ga4.firebase_app_id'),
'queue_connection' => config('filament-short-url.queue_connection', 'sync'),
'queue_name' => config('filament-short-url.queue_name', 'default'),
'cache_ttl' => config('filament-short-url.cache_ttl', 3600),
'counter_buffering_enabled' => config('filament-short-url.counter_buffering.enabled', false),
'trust_cdn_headers' => config('filament-short-url.trust_cdn_headers', false),
'pruning_enabled' => config('filament-short-url.pruning.enabled', true),
'pruning_retention_days' => config('filament-short-url.pruning.retention_days', 90),
'rate_limiting_enabled' => config('filament-short-url.rate_limiting.enabled', false),
'rate_limiting_max_attempts' => config('filament-short-url.rate_limiting.max_attempts', 60),
'rate_limiting_decay_seconds' => config('filament-short-url.rate_limiting.decay_seconds', 60),
'tracking_enabled' => config('filament-short-url.tracking.enabled', true),
'tracking_fields_ip_address' => config('filament-short-url.tracking.fields.ip_address', true),
'tracking_fields_browser' => config('filament-short-url.tracking.fields.browser', true),
'tracking_fields_browser_version' => config('filament-short-url.tracking.fields.browser_version', true),
'tracking_fields_operating_system' => config('filament-short-url.tracking.fields.operating_system', true),
'tracking_fields_operating_system_version' => config('filament-short-url.tracking.fields.operating_system_version', true),
'tracking_fields_referer_url' => config('filament-short-url.tracking.fields.referer_url', true),
'tracking_fields_device_type' => config('filament-short-url.tracking.fields.device_type', true),
'qr_size' => config('filament-short-url.qr_defaults.size', 300),
'qr_margin' => config('filament-short-url.qr_defaults.margin', 1),
'qr_dot_style' => config('filament-short-url.qr_defaults.dot_style', 'square'),
'qr_foreground_color' => config('filament-short-url.qr_defaults.foreground_color', '#000000'),
'qr_background_color' => config('filament-short-url.qr_defaults.background_color', '#ffffff'),
'qr_gradient_enabled' => config('filament-short-url.qr_defaults.gradient_enabled', false),
'qr_gradient_from' => config('filament-short-url.qr_defaults.gradient_from', '#4f46e5'),
'qr_gradient_to' => config('filament-short-url.qr_defaults.gradient_to', '#06b6d4'),
'qr_gradient_type' => config('filament-short-url.qr_defaults.gradient_type', 'linear'),
'global_webhook_url' => null,
'webhook_events' => ['visited'],
'api_keys' => [],
'api_enabled' => false,
'site_name' => config('filament-short-url.site_name'),
// Security v2.0
'vpn_detection_enabled' => config('filament-short-url.vpn_detection.enabled', false),
'vpn_detection_driver' => config('filament-short-url.vpn_detection.driver', 'ip-api'),
'vpnapi_key' => config('filament-short-url.vpn_detection.vpnapi_key'),
'vpn_block_action' => config('filament-short-url.vpn_detection.block_action', 'flag_only'),
'safe_browsing_enabled' => config('filament-short-url.safe_browsing.enabled', false),
'google_safe_browsing_api_key' => config('filament-short-url.safe_browsing.api_key'),
], $stored);
return $this->cache;
@@ -73,6 +112,8 @@ class ShortUrlSettingsManager
File::makeDirectory($dir, 0755, true);
}
$oldPrefix = $this->get('route_prefix');
// Keep only supported settings keys to prevent bloat
$keys = [
'route_prefix',
@@ -83,10 +124,48 @@ class ShortUrlSettingsManager
'geo_ip_cache_ttl',
'geo_ip_timeout',
'maxmind_database_path',
'geo_ip_stats_cache_ttl',
'ga4_api_secret',
'ga4_firebase_app_id',
'queue_connection',
'queue_name',
'cache_ttl',
'counter_buffering_enabled',
'trust_cdn_headers',
'pruning_enabled',
'pruning_retention_days',
'rate_limiting_enabled',
'rate_limiting_max_attempts',
'rate_limiting_decay_seconds',
'tracking_enabled',
'tracking_fields_ip_address',
'tracking_fields_browser',
'tracking_fields_browser_version',
'tracking_fields_operating_system',
'tracking_fields_operating_system_version',
'tracking_fields_referer_url',
'tracking_fields_device_type',
'qr_size',
'qr_margin',
'qr_dot_style',
'qr_foreground_color',
'qr_background_color',
'qr_gradient_enabled',
'qr_gradient_from',
'qr_gradient_to',
'qr_gradient_type',
'global_webhook_url',
'webhook_events',
'api_keys',
'api_enabled',
'site_name',
// Security v2.0
'vpn_detection_enabled',
'vpn_detection_driver',
'vpnapi_key',
'vpn_block_action',
'safe_browsing_enabled',
'google_safe_browsing_api_key',
];
$filtered = array_intersect_key($data, array_flip($keys));
@@ -107,15 +186,96 @@ class ShortUrlSettingsManager
if (isset($filtered['geo_ip_timeout'])) {
$filtered['geo_ip_timeout'] = (int) $filtered['geo_ip_timeout'];
}
if (isset($filtered['geo_ip_stats_cache_ttl'])) {
$filtered['geo_ip_stats_cache_ttl'] = (int) $filtered['geo_ip_stats_cache_ttl'];
}
if (isset($filtered['cache_ttl'])) {
$filtered['cache_ttl'] = (int) $filtered['cache_ttl'];
}
if (isset($filtered['counter_buffering_enabled'])) {
$filtered['counter_buffering_enabled'] = (bool) $filtered['counter_buffering_enabled'];
}
if (isset($filtered['trust_cdn_headers'])) {
$filtered['trust_cdn_headers'] = (bool) $filtered['trust_cdn_headers'];
}
if (isset($filtered['pruning_enabled'])) {
$filtered['pruning_enabled'] = (bool) $filtered['pruning_enabled'];
}
if (isset($filtered['pruning_retention_days'])) {
$filtered['pruning_retention_days'] = (int) $filtered['pruning_retention_days'];
}
if (isset($filtered['rate_limiting_enabled'])) {
$filtered['rate_limiting_enabled'] = (bool) $filtered['rate_limiting_enabled'];
}
if (isset($filtered['rate_limiting_max_attempts'])) {
$filtered['rate_limiting_max_attempts'] = (int) $filtered['rate_limiting_max_attempts'];
}
if (isset($filtered['rate_limiting_decay_seconds'])) {
$filtered['rate_limiting_decay_seconds'] = (int) $filtered['rate_limiting_decay_seconds'];
}
// Tracking defaults
if (isset($filtered['tracking_enabled'])) {
$filtered['tracking_enabled'] = (bool) $filtered['tracking_enabled'];
}
if (isset($filtered['tracking_fields_ip_address'])) {
$filtered['tracking_fields_ip_address'] = (bool) $filtered['tracking_fields_ip_address'];
}
if (isset($filtered['tracking_fields_browser'])) {
$filtered['tracking_fields_browser'] = (bool) $filtered['tracking_fields_browser'];
}
if (isset($filtered['tracking_fields_browser_version'])) {
$filtered['tracking_fields_browser_version'] = (bool) $filtered['tracking_fields_browser_version'];
}
if (isset($filtered['tracking_fields_operating_system'])) {
$filtered['tracking_fields_operating_system'] = (bool) $filtered['tracking_fields_operating_system'];
}
if (isset($filtered['tracking_fields_operating_system_version'])) {
$filtered['tracking_fields_operating_system_version'] = (bool) $filtered['tracking_fields_operating_system_version'];
}
if (isset($filtered['tracking_fields_referer_url'])) {
$filtered['tracking_fields_referer_url'] = (bool) $filtered['tracking_fields_referer_url'];
}
if (isset($filtered['tracking_fields_device_type'])) {
$filtered['tracking_fields_device_type'] = (bool) $filtered['tracking_fields_device_type'];
}
// QR defaults
if (isset($filtered['qr_size'])) {
$filtered['qr_size'] = (int) $filtered['qr_size'];
}
if (isset($filtered['qr_margin'])) {
$filtered['qr_margin'] = (int) $filtered['qr_margin'];
}
if (isset($filtered['qr_gradient_enabled'])) {
$filtered['qr_gradient_enabled'] = (bool) $filtered['qr_gradient_enabled'];
}
// Security v2.0 casts
if (isset($filtered['vpn_detection_enabled'])) {
$filtered['vpn_detection_enabled'] = (bool) $filtered['vpn_detection_enabled'];
}
if (isset($filtered['safe_browsing_enabled'])) {
$filtered['safe_browsing_enabled'] = (bool) $filtered['safe_browsing_enabled'];
}
File::put($path, json_encode($filtered, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
$this->cache = null;
// Apply immediately to current request config
$this->applyConfigOverrides();
// Clear route cache if route prefix has changed
$newPrefix = $filtered['route_prefix'] ?? null;
if ($oldPrefix !== null && $newPrefix !== null && $oldPrefix !== $newPrefix) {
try {
if (app()->routesAreCached()) {
Artisan::call('route:clear');
}
} catch (\Throwable) {
// Ignore route clear errors during boot/test
}
}
}
/**
@@ -134,10 +294,49 @@ class ShortUrlSettingsManager
'filament-short-url.geo_ip.cache_ttl' => $settings['geo_ip_cache_ttl'],
'filament-short-url.geo_ip.timeout' => $settings['geo_ip_timeout'],
'filament-short-url.geo_ip.maxmind.database_path' => $settings['maxmind_database_path'],
'filament-short-url.geo_ip.stats_cache_ttl' => $settings['geo_ip_stats_cache_ttl'],
'filament-short-url.ga4.api_secret' => $settings['ga4_api_secret'],
'filament-short-url.ga4.firebase_app_id' => $settings['ga4_firebase_app_id'],
'filament-short-url.queue_connection' => $settings['queue_connection'],
'filament-short-url.queue_name' => $settings['queue_name'],
'filament-short-url.cache_ttl' => $settings['cache_ttl'],
'filament-short-url.counter_buffering.enabled' => $settings['counter_buffering_enabled'],
'filament-short-url.trust_cdn_headers' => $settings['trust_cdn_headers'],
'filament-short-url.pruning.enabled' => $settings['pruning_enabled'],
'filament-short-url.pruning.retention_days' => $settings['pruning_retention_days'],
'filament-short-url.rate_limiting.enabled' => $settings['rate_limiting_enabled'],
'filament-short-url.rate_limiting.max_attempts' => $settings['rate_limiting_max_attempts'],
'filament-short-url.rate_limiting.decay_seconds' => $settings['rate_limiting_decay_seconds'],
'filament-short-url.tracking.enabled' => $settings['tracking_enabled'],
'filament-short-url.tracking.fields.ip_address' => $settings['tracking_fields_ip_address'],
'filament-short-url.tracking.fields.browser' => $settings['tracking_fields_browser'],
'filament-short-url.tracking.fields.browser_version' => $settings['tracking_fields_browser_version'],
'filament-short-url.tracking.fields.operating_system' => $settings['tracking_fields_operating_system'],
'filament-short-url.tracking.fields.operating_system_version' => $settings['tracking_fields_operating_system_version'],
'filament-short-url.tracking.fields.referer_url' => $settings['tracking_fields_referer_url'],
'filament-short-url.tracking.fields.device_type' => $settings['tracking_fields_device_type'],
'filament-short-url.qr_defaults.size' => $settings['qr_size'],
'filament-short-url.qr_defaults.margin' => $settings['qr_margin'],
'filament-short-url.qr_defaults.dot_style' => $settings['qr_dot_style'],
'filament-short-url.qr_defaults.foreground_color' => $settings['qr_foreground_color'],
'filament-short-url.qr_defaults.background_color' => $settings['qr_background_color'],
'filament-short-url.qr_defaults.gradient_enabled' => $settings['qr_gradient_enabled'],
'filament-short-url.qr_defaults.gradient_from' => $settings['qr_gradient_from'],
'filament-short-url.qr_defaults.gradient_to' => $settings['qr_gradient_to'],
'filament-short-url.qr_defaults.gradient_type' => $settings['qr_gradient_type'],
'filament-short-url.global_webhook_url' => $settings['global_webhook_url'] ?? null,
'filament-short-url.webhook_events' => $settings['webhook_events'] ?? ['visited'],
'filament-short-url.api_enabled' => (bool) ($settings['api_enabled'] ?? false),
'filament-short-url.site_name' => $settings['site_name'] ?? null,
// Security v2.0
'filament-short-url.vpn_detection.enabled' => (bool) ($settings['vpn_detection_enabled'] ?? false),
'filament-short-url.vpn_detection.driver' => $settings['vpn_detection_driver'] ?? 'ip-api',
'filament-short-url.vpn_detection.vpnapi_key' => $settings['vpnapi_key'] ?? null,
'filament-short-url.vpn_detection.block_action' => $settings['vpn_block_action'] ?? 'flag_only',
'filament-short-url.vpn_detection.cache_ttl' => 86400,
'filament-short-url.vpn_detection.timeout' => 2,
'filament-short-url.safe_browsing.enabled' => (bool) ($settings['safe_browsing_enabled'] ?? false),
'filament-short-url.safe_browsing.api_key' => $settings['google_safe_browsing_api_key'] ?? null,
]);
}
}

View File

@@ -16,6 +16,7 @@ class ShortUrlTracker
public function __construct(
private readonly UserAgentParser $uaParser,
private readonly GeoIpService $geoIp,
private readonly ProxyDetectionService $proxyDetector,
) {}
/**
@@ -23,21 +24,35 @@ class ShortUrlTracker
*
* Returns null if the visit was from a bot/crawler (we don't track those).
*/
public function record(ShortUrl $shortUrl, Request $request, ?string $preResolvedCountryCode = null): ?ShortUrlVisit
{
public function record(
ShortUrl $shortUrl,
Request $request,
?string $preResolvedCountryCode = null,
?string $preResolvedCity = null,
?string $utmSource = null,
?string $utmMedium = null,
?string $utmCampaign = null,
?string $utmTerm = null,
?string $utmContent = null,
): ?ShortUrlVisit {
$ip = ClientIpExtractor::getIp($request);
$ipHash = hash('sha256', $ip);
$ua = $request->userAgent() ?? '';
$parsed = $this->uaParser->parse($ua);
// Don't track bots — they inflate stats and waste API calls
if ($parsed['device_type'] === 'robot') {
return null;
// Run bot & proxy/VPN detection
$isBot = $parsed['device_type'] === 'robot';
$isProxy = false;
if (! $isBot) {
$detection = $this->proxyDetector->detect($ip);
$isBot = (bool) $detection['is_bot'];
$isProxy = (bool) $detection['is_proxy'];
}
$geo = config('filament-short-url.geo_ip.enabled', true)
? $this->geoIp->resolve($ip, $preResolvedCountryCode)
: ['country' => null, 'country_code' => null];
? $this->geoIp->resolve($ip, $preResolvedCountryCode, $preResolvedCity)
: ['country' => null, 'country_code' => null, 'city' => null];
// Determine uniqueness: first time this IP hash visits this URL.
// We check BEFORE insert to avoid a self-referential race.
@@ -56,13 +71,51 @@ class ShortUrlTracker
$visit->operating_system_version = $shortUrl->track_operating_system_version
? $parsed['operating_system_version'] : null;
$visit->device_type = $shortUrl->track_device_type ? $parsed['device_type'] : null;
$visit->referer_url = $shortUrl->track_referer_url ? $request->header('Referer') : null;
$visit->country = $geo['country'];
$visit->country_code = $geo['country_code'];
$visit->city = $geo['city'] ?? null;
$visit->is_bot = $isBot;
$visit->is_proxy = $isProxy;
$visit->utm_source = $utmSource;
$visit->utm_medium = $utmMedium;
$visit->utm_campaign = $utmCampaign;
$visit->utm_term = $utmTerm;
$visit->utm_content = $utmContent;
// Clean & normalize referer URL to host domain
if ($shortUrl->track_referer_url && $referer = $request->header('Referer')) {
$visit->referer_url = $referer;
$refererHost = parse_url($referer, PHP_URL_HOST);
if ($refererHost) {
$refererHost = preg_replace('/^www\./', '', strtolower($refererHost));
if (str_contains($refererHost, 'facebook.com')) {
$refererHost = 'facebook.com';
} elseif (str_contains($refererHost, 'linkedin.com')) {
$refererHost = 'linkedin.com';
} elseif (str_contains($refererHost, 'twitter.com') || str_contains($refererHost, 't.co')) {
$refererHost = 'twitter.com';
} elseif (str_contains($refererHost, 'google.')) {
$refererHost = 'google.com';
} elseif (str_contains($refererHost, 'instagram.com')) {
$refererHost = 'instagram.com';
} elseif (str_contains($refererHost, 'youtube.com')) {
$refererHost = 'youtube.com';
}
$visit->referer_host = $refererHost;
} else {
$visit->referer_host = 'Direct';
}
} else {
$visit->referer_host = 'Direct';
}
$visit->save();
$shortUrl->incrementVisits($isUnique);
// Increment stats only if it's NOT a bot or proxy/VPN to keep analytics clean
if (! $isBot && ! $isProxy) {
$shortUrl->incrementVisits($isUnique);
}
return $visit;
}