feat: Initial MoneyFlix project setup

- Created separate MoneyFlix project directory
- Copied Node.js redirector from production server
- Added CRM PHP code (Redirects module, Core classes, Config, Routes, Views)
- Created comprehensive documentation (README_MONEYFLIX.md)
- Added sync script to keep CRM code updated (sync-from-crm.sh)
- Configured .gitignore for Node.js and PHP
- Set up proper project structure for multi-client isolation

This separates MoneyFlix from the main CRM to avoid confusion
between different client systems and provides a dedicated
environment for MoneyFlix-specific development and maintenance.
This commit is contained in:
1sonhador committed 2025-10-03 12:09:41 +01:00
commit 9d43854277
3716 files changed
+582570

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
# MoneyFlix .gitignore
# Node.js
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Logs
logs/
*.log
# Runtime data
pids/
*.pid
*.seed
*.pid.lock
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# PM2
.pm2/
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# IDE
.vscode/
.idea/
*.swp
*.swo
# Temporary files
tmp/
temp/
# Database
*.sqlite
*.db
# Backup files
*.bak
*.backup
# CRM specific (cópia local)
crm/vendor/
crm/storage/
crm/cache/
crm/logs/
+208
View File
@@ -0,0 +1,208 @@
# MoneyFlix Redirector
High-performance NodeJS redirect service with MySQL analytics for the MoneyFlix CRM system.
## 🚀 Features
- **High Performance**: Handles millions of redirects with queue-based processing
- **MySQL Analytics**: Direct database logging with User Agent parsing
- **Real-time Cache**: 30-second redirect cache with automatic refresh
- **Queue System**: Batch processing with retry logic for reliability
- **User Agent Analysis**: Detailed device, browser, and OS detection
- **Health Monitoring**: Built-in status and health check endpoints
## 📁 Project Structure
```
moneyflix-redirector/
├── index.mjs # Main application entry point
├── db/
│ └── logUser.mjs # MySQL logging and queue system
├── helpers/
│ ├── helpers.mjs # CRM API integration
│ └── userAgentParser.mjs # User Agent parsing
├── ecosystem.config.js # PM2 configuration
├── package.json # Dependencies
└── README.md # This file
```
## 🛠️ Installation
1. **Install dependencies:**
```bash
npm install
```
2. **Configure environment:**
```bash
cp env.example .env
# Edit .env with your configuration
```
3. **Start with PM2:**
```bash
pm2 start ecosystem.config.js
```
## ⚙️ Configuration
### Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `NODE_ENV` | `production` | Environment mode |
| `PORT` | `3000` | Server port |
| `CRM_API_URL` | `https://redirect.moneyflix.com/api/redirects` | CRM API endpoint |
| `CRM_API_KEY` | `moneyflix-api-key-2024` | API authentication key |
| `DB_HOST` | `127.0.0.1` | MySQL host |
| `DB_PORT` | `3306` | MySQL port |
| `DB_USER` | `root` | MySQL username |
| `DB_PASSWORD` | - | MySQL password |
| `DB_DATABASE` | `bitreport_redirects` | MySQL database name |
| `QUEUE_MAX_SIZE` | `1000` | Maximum queue size |
| `QUEUE_FLUSH_INTERVAL` | `5000` | Queue flush interval (ms) |
| `CACHE_TTL` | `30000` | Redirect cache TTL (ms) |
## 🔗 API Endpoints
### Redirect
```
GET /:slug
```
Redirects to the target URL for the given slug.
### Health Check
```
GET /health
```
Returns service health status and basic metrics.
### Status
```
GET /status
```
Returns detailed status including queue and database statistics.
## 📊 Database Schema
The service logs hits to the `redirect_hits` table:
```sql
CREATE TABLE redirect_hits (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
redirect_id BIGINT NOT NULL,
ip_address VARCHAR(45) NOT NULL,
user_agent TEXT,
referer TEXT,
destination_url TEXT NOT NULL,
response_time INT DEFAULT 0,
status VARCHAR(50) DEFAULT 'redirected',
geo VARCHAR(10) DEFAULT 'Unknown',
browser VARCHAR(100) DEFAULT 'Unknown',
os VARCHAR(100) DEFAULT 'Unknown',
device VARCHAR(50) DEFAULT 'Unknown',
is_mobile TINYINT(1) DEFAULT 0,
is_bot TINYINT(1) DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_redirect_id (redirect_id),
INDEX idx_ip_address (ip_address),
INDEX idx_created_at (created_at),
INDEX idx_redirect_created (redirect_id, created_at)
);
```
## 🚀 Performance Features
### Queue System
- **Batch Processing**: Groups hits for efficient MySQL inserts
- **Auto Flush**: Processes queue every 5 seconds or when full
- **Retry Logic**: Failed hits are retried up to 3 times
- **Memory Efficient**: Configurable queue size limits
### Caching
- **Redirect Cache**: 30-second TTL for redirect definitions
- **Auto Refresh**: Background updates from CRM API
- **Memory Efficient**: Only stores active redirects
### User Agent Analysis
- **Device Detection**: Mobile, tablet, desktop classification
- **Browser Parsing**: Name, version, and engine detection
- **OS Detection**: Operating system and version parsing
- **Bot Detection**: Automatic crawler and bot identification
## 📈 Monitoring
### Queue Statistics
```javascript
{
queueSize: 42,
isProcessing: false,
maxSize: 1000,
flushInterval: 5000
}
```
### Database Statistics
```javascript
{
total_hits: 15420,
unique_redirects: 15,
unique_ips: 8923,
mobile_hits: 8234,
bot_hits: 234,
last_hit: "2024-01-15T10:30:45.000Z"
}
```
## 🔧 Development
### Local Development
```bash
npm run dev
```
### Production Deployment
```bash
npm start
# or
pm2 start ecosystem.config.js
```
### Testing
```bash
# Test redirect
curl http://localhost:3000/mf_bonus
# Check health
curl http://localhost:3000/health
# Check status
curl http://localhost:3000/status
```
## 📝 Logs
Logs are stored in the `logs/` directory:
- `combined.log` - All logs
- `out.log` - Standard output
- `error.log` - Error logs
## 🚨 Error Handling
- **Graceful Shutdown**: Flushes remaining hits on SIGTERM/SIGINT
- **Connection Pooling**: Automatic reconnection to MySQL
- **API Fallback**: Continues working even if CRM API is down
- **Queue Recovery**: Retries failed database operations
## 📊 Analytics Data
Each redirect hit includes:
- **Basic Info**: IP, User Agent, Referer, Response Time
- **Device Data**: Browser, OS, Device Type, Mobile Detection
- **Bot Detection**: Automatic crawler identification
- **Geographic**: Country code (if available)
- **Performance**: Response time and status
---
**Built by BitReport for MoneyFlix CRM System**
+218
View File
@@ -0,0 +1,218 @@
# MoneyFlix Redirector System
## 📋 Visão Geral
Sistema de redirecionamento dedicado para o cliente MoneyFlix, separado do CRM principal para evitar confusões entre múltiplos clientes.
## 🏗️ Arquitetura
### Servidor de Produção
- **IP**: 94.23.75.89
- **Domínio**: redirect.moneyflix.com
- **Porta Node.js**: 3001
- **Processo PM2**: moneyflix-redirector
### Configuração Nginx
```nginx
# /etc/nginx/sites-enabled/redirect.moneyflix.com.conf
server {
listen 80;
listen 443 ssl http2;
server_name redirect.moneyflix.com;
# Redirects API - NodeJS (port 3001)
location /r/ {
proxy_pass http://localhost:3001/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Health check
location /health {
proxy_pass http://localhost:3001/health;
}
# Status check
location /status {
proxy_pass http://localhost:3001/status;
}
# Default - PHP CRM
location / {
root /var/www/html;
try_files $uri $uri/ /index.php?$query_string;
}
}
```
## 🔧 Configuração
### Variáveis de Ambiente (.env)
```bash
# API Configuration
CRM_API_URL=http://94.23.75.89/api/redirects
CRM_API_KEY=moneyflix-api-key-2024
# Server Configuration
PORT=3001
NODE_ENV=production
# Database (if needed)
DB_HOST=localhost
DB_USER=moneyflix_user
DB_PASS=moneyflix_password
DB_NAME=moneyflix_db
```
### Estrutura de Ficheiros
```
MoneyFlix/
├── index.mjs # Aplicação principal Node.js
├── package.json # Dependências Node.js
├── ecosystem.config.cjs # Configuração PM2
├── deploy.sh # Script de deploy
├── sync-from-crm.sh # Script de sincronização com CRM
├── helpers/ # Funções auxiliares Node.js
│ └── helpers.mjs # fetchRedirects, etc.
├── db/ # Scripts de base de dados
├── logs/ # Logs da aplicação
├── crm/ # Código PHP do CRM (cópia)
│ ├── Redirects/ # Módulo de Redirects
│ ├── Core/ # Classes core do CRM
│ ├── Config/ # Configurações
│ ├── Routes/ # Rotas da API
│ ├── Views/ # Views PHP
│ ├── composer.json # Dependências PHP
│ └── config.env.example # Configuração de ambiente
└── README_MONEYFLIX.md # Esta documentação
```
## 🚀 Deploy
### Deploy Manual
```bash
# No servidor (94.23.75.89)
cd /opt/moneyflix-redirector
git pull origin main
npm install
pm2 restart moneyflix-redirector
```
### Deploy via Script
```bash
# Local
./deploy.sh
```
## 🔄 API de Redirects
### Endpoint
- **URL**: `http://94.23.75.89/api/redirects`
- **Método**: GET
- **Headers**:
- `Authorization: Bearer moneyflix-api-key-2024`
- `Host: redirect.moneyflix.com`
### Resposta
```json
{
"success": true,
"data": [
{
"id": 17,
"cuid": "evento18outubro25",
"name": "evento-18-outubro",
"source_url": "",
"target_url": "https://moneyflix.com/evento-18-outubro",
"status": 1,
"redirect_type": 302,
"tracking_enabled": 1
}
]
}
```
## 🐛 Troubleshooting
### Problema: Redirect não encontrado
```bash
# Verificar se o redirect existe na base de dados
curl -s 'http://94.23.75.89/api/redirects' -H 'Host: redirect.moneyflix.com'
# Verificar logs do Node.js
pm2 logs moneyflix-redirector --lines 50
# Verificar se o PM2 está a correr
pm2 status
```
### Problema: CloudFlare bloqueia API
- **Solução**: Usar IP direto (94.23.75.89) em vez do domínio
- **Configuração**: `CRM_API_URL=http://94.23.75.89/api/redirects`
- **Header**: Adicionar `Host: redirect.moneyflix.com`
## 📊 Monitorização
### Health Check
```bash
curl https://redirect.moneyflix.com/health
```
### Status Check
```bash
curl https://redirect.moneyflix.com/status
```
### Logs
```bash
# Ver logs em tempo real
pm2 logs moneyflix-redirector
# Ver logs específicos
tail -f /opt/moneyflix-redirector/logs/app.log
```
## 🔗 Integração com CRM
### Sincronização de Redirects
O sistema carrega redirects da API do CRM principal:
- **Fonte**: `http://94.23.75.89/api/redirects`
- **Frequência**: A cada 5 minutos (configurável)
- **Cache**: Em memória para performance
### Sincronização de Código
Para manter o código PHP do CRM atualizado:
```bash
# Executar script de sincronização
./sync-from-crm.sh
```
Este script copia os ficheiros relevantes do CRM principal:
- Módulo Redirects (Controllers, Models, Views)
- Classes Core (DatabaseManager, BaseController, etc.)
- Configurações e Routes
- Dependências PHP (composer.json)
### Base de Dados
- **Tabela**: `redirects`
- **Campos principais**: `cuid`, `target_url`, `status`
- **Filtro**: `status >= 0` (apenas ativos)
## ⚠️ Notas Importantes
1. **Isolamento**: Este sistema é completamente separado do CRM principal
2. **CloudFlare**: Usar IP direto para evitar bloqueios internos
3. **PM2**: Processo `moneyflix-redirector` deve estar sempre ativo
4. **Logs**: Verificar logs regularmente para problemas
5. **Backup**: Manter cópia local dos ficheiros de configuração
## 📞 Suporte
Para problemas relacionados com o MoneyFlix Redirector:
1. Verificar logs do PM2
2. Testar API de redirects diretamente
3. Verificar configuração Nginx
4. Confirmar que o redirect existe na base de dados
Executable
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
# MoneyFlix Redirector Cleanup Script
# Removes old deployment packages, keeping only the last 5
echo "🧹 Cleaning up old deployment packages..."
# Keep only the last 5 deployment packages
cd _deploy
ls -t moneyflix-redirector-*.tar.gz 2>/dev/null | tail -n +6 | xargs rm -f
echo "✅ Cleanup completed!"
echo "📦 Remaining packages:"
ls -la moneyflix-redirector-*.tar.gz 2>/dev/null || echo "No packages found"
+13
View File
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Config;
class Constants
{
public const SCHEDULED_TASKS_TABLE = 'scheduled_tasks';
public const INTERPRETER_PHP = '/opt/homebrew/bin/php';
public const INTERPRETER_NODE = '/opt/homebrew/bin/node';
public const INTERPRETER_SHELL = '/bin/bash';
public const INTERPRETER_PYTHON = '/opt/homebrew/bin/python3';
}
+105
View File
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
// app/Config/branding.php
return [
/**
* Hostname-specific configurations.
* Usa string única (hostnames separados por vírgula) como chave para evitar erro de offset.
* O sistema de matching deve explodir a chave e fazer fnmatch para cada entrada.
*/
// WDMI branding para wdmi.pt, subdomínios, localhost (dev) e servidor WDMI
'wdmi.pt,www.wdmi.pt,*.wdmi.pt,localhost,192.168.1.69' => [
'client_id' => 'wdmi',
'company_name' => 'WDMI',
'logo_url' => 'https://static.lvengine.net/wdmi2024/interface/imgs/logo-white.png',
'favicon_url' => '/assets/images/favicon.ico',
'theme_color' => '#405189',
'theme_variants' => [
'data-layout' => 'vertical',
'data-bs-theme' => 'light',
'data-sidebar' => 'gradient',
'data-sidebar-size' => 'lg',
'data-layout-style' => 'default',
'data-topbar' => 'dark',
'data-layout-width' => 'fluid',
'data-layout-position' => 'fixed',
'data-sidebar-image' => 'none',
'data-preloader' => 'enable'
]
],
// MoneyFlix
'moneyflix.pt,www.moneyflix.pt,*.moneyflix.pt,*.moneyflix.com,redirect.moneyflix.com,localhost-moneyflix' => [
'client_id' => 'moneyflix',
'company_name' => 'MoneyFlix',
'logo_url' => '/assets/images/moneyflix-dark.png',
'logo_light' => '/assets/images/moneyflix-light.png',
'logo_dark' => '/assets/images/moneyflix-dark.png',
'favicon_url' => 'https://moneyflix.pt/favicon.ico',
'company_url' => 'https://moneyflix.pt',
'support_email' => '[email protected]',
'theme_color' => '#22c55e',
'theme_variants' => [
'data-layout' => 'vertical',
'data-bs-theme' => 'dark',
'data-sidebar' => 'dark',
'data-sidebar-size' => 'lg',
'data-layout-style' => 'default',
'data-topbar' => 'dark',
'data-layout-width' => 'fluid',
'data-layout-position' => 'fixed',
'data-sidebar-image' => 'none',
'data-preloader' => 'enable'
]
],
// Performix (inclui BetZoo - adquirido)
'analytics.performix.com,*.performix.com,performixmedia.com,*.performixmedia.com,*.betzoo.com,betzoo.com,localhost-performix,localhost-betzoo' => [
'client_id' => 'performix',
'company_name' => 'Performix',
'logo_url' => '/assets/images/performix-logo.png',
'logo_light' => '/assets/images/performix-logo-light.png',
'logo_dark' => '/assets/images/performix-logo-dark.png',
'favicon_url' => '/assets/images/clients/performix-favicon.ico',
'theme_color' => '#3b82f6',
'theme_variants' => [
'data-layout' => 'vertical',
'data-bs-theme' => 'light',
'data-sidebar' => 'light',
'data-sidebar-size' => 'lg',
'data-layout-style' => 'default',
'data-topbar' => 'light',
'data-layout-width' => 'fluid',
'data-layout-position' => 'fixed',
'data-sidebar-image' => 'none',
'data-preloader' => 'enable'
]
],
/**
* Fallback configuration for unmatched hostnames.
* Alterado para usar WDMI como padrão
*/
'default' => [
'client_id' => 'wdmi',
'company_name' => 'WDMI',
'logo_url' => 'https://static.lvengine.net/wdmi2024/interface/imgs/logo-white.png',
'favicon_url' => '/assets/images/favicon.ico',
'theme_color' => '#405189',
'theme_variants' => [
'data-layout' => 'vertical',
'data-bs-theme' => 'light',
'data-sidebar' => 'gradient',
'data-sidebar-size' => 'lg',
'data-layout-style' => 'default',
'data-topbar' => 'dark',
'data-layout-width' => 'fluid',
'data-layout-position' => 'fixed',
'data-sidebar-image' => 'none',
'data-preloader' => 'enable'
]
]
];
+487
View File
@@ -0,0 +1,487 @@
<?php
declare(strict_types=1);
namespace App\Core;
use Exception;
use Visus\Cuid2\Cuid2;
/**
* Sistema de Alertas Proativo
*
* Monitoriza a aplicação e envia alertas quando detecta problemas
* ou condições que requerem atenção imediata.
*/
class AlertManager
{
private Logger $logger;
private array $config;
private array $thresholds;
private array $alertHistory;
public function __construct()
{
$this->logger = new Logger();
$this->config = $this->loadConfig();
$this->thresholds = $this->config['thresholds'] ?? [];
$this->alertHistory = [];
}
/**
* Carregar configuração de alertas
*/
private function loadConfig(): array
{
$configFile = __DIR__ . '/../../config/alerts.php';
if (file_exists($configFile)) {
return require $configFile;
}
// Configuração padrão
return [
'enabled' => true,
'email' => [
'enabled' => false,
'to' => '[email protected]',
'from' => '[email protected]'
],
'thresholds' => [
'performance' => [
'response_time' => 2.0, // segundos
'memory_usage' => 80, // percentagem
'disk_usage' => 85 // percentagem
],
'security' => [
'failed_logins' => 5, // tentativas
'suspicious_ips' => 3 // IPs diferentes
],
'errors' => [
'critical_errors' => 3, // erros por hora
'database_errors' => 2 // erros por hora
]
],
'cooldown' => [
'performance' => 300, // 5 minutos
'security' => 600, // 10 minutos
'errors' => 1800 // 30 minutos
]
];
}
/**
* Verificar performance da aplicação
*/
public function checkPerformance(float $responseTime, ?float $memoryUsage = null): void
{
if (!$this->config['enabled']) return;
$threshold = $this->thresholds['performance']['response_time'] ?? 2.0;
if ($responseTime > $threshold) {
$this->triggerAlert('performance', 'response_time', [
'current' => $responseTime,
'threshold' => $threshold,
'message' => "Tempo de resposta lento: {$responseTime}s (limite: {$threshold}s)"
]);
}
// Verificar uso de memória se fornecido
if ($memoryUsage !== null) {
$memoryThreshold = $this->thresholds['performance']['memory_usage'] ?? 80;
if ($memoryUsage > $memoryThreshold) {
$this->triggerAlert('performance', 'memory_usage', [
'current' => $memoryUsage,
'threshold' => $memoryThreshold,
'message' => "Uso de memória alto: {$memoryUsage}% (limite: {$memoryThreshold}%)"
]);
}
}
}
/**
* Verificar segurança
*/
public function checkSecurity(string $event, array $context = []): void
{
if (!$this->config['enabled']) return;
switch ($event) {
case 'failed_login':
$this->checkFailedLogins($context);
break;
case 'suspicious_activity':
$this->checkSuspiciousActivity($context);
break;
case 'unauthorized_access':
$this->triggerAlert('security', 'unauthorized_access', [
'ip' => $context['ip'] ?? 'unknown',
'endpoint' => $context['endpoint'] ?? 'unknown',
'message' => 'Tentativa de acesso não autorizado'
]);
break;
}
}
/**
* Verificar tentativas de login falhadas
*/
private function checkFailedLogins(array $context): void
{
$ip = $context['ip'] ?? 'unknown';
$threshold = $this->thresholds['security']['failed_logins'] ?? 5;
// Contar tentativas falhadas por IP (simplificado)
$failedLogins = $this->getFailedLoginsCount($ip);
if ($failedLogins >= $threshold) {
$this->triggerAlert('security', 'failed_logins', [
'ip' => $ip,
'count' => $failedLogins,
'threshold' => $threshold,
'message' => "Múltiplas tentativas de login falhadas do IP {$ip}: {$failedLogins} tentativas"
]);
}
}
/**
* Verificar atividade suspeita
*/
private function checkSuspiciousActivity(array $context): void
{
$ip = $context['ip'] ?? 'unknown';
$threshold = $this->thresholds['security']['suspicious_ips'] ?? 3;
// Verificar se o IP está na lista de suspeitos
$suspiciousCount = $this->getSuspiciousIPCount($ip);
if ($suspiciousCount >= $threshold) {
$this->triggerAlert('security', 'suspicious_activity', [
'ip' => $ip,
'count' => $suspiciousCount,
'threshold' => $threshold,
'message' => "Atividade suspeita detectada do IP {$ip}"
]);
}
}
/**
* Verificar erros críticos
*/
public function checkErrors(string $errorType, array $context = []): void
{
if (!$this->config['enabled']) return;
$threshold = $this->thresholds['errors'][$errorType] ?? 3;
$errorCount = $this->getErrorCount($errorType);
if ($errorCount >= $threshold) {
$this->triggerAlert('errors', $errorType, [
'count' => $errorCount,
'threshold' => $threshold,
'message' => "Múltiplos erros {$errorType}: {$errorCount} erros (limite: {$threshold})",
'context' => $context
]);
}
}
/**
* Verificar saúde do sistema
*/
public function checkSystemHealth(): void
{
if (!$this->config['enabled']) return;
// Verificar espaço em disco
$diskUsage = $this->getDiskUsage();
$diskThreshold = $this->thresholds['performance']['disk_usage'] ?? 85;
if ($diskUsage > $diskThreshold) {
$this->triggerAlert('performance', 'disk_usage', [
'current' => $diskUsage,
'threshold' => $diskThreshold,
'message' => "Espaço em disco crítico: {$diskUsage}% (limite: {$diskThreshold}%)"
]);
}
// Verificar conectividade da base de dados
$this->checkDatabaseConnection();
}
/**
* Verificar conectividade da base de dados
*/
private function checkDatabaseConnection(): void
{
try {
$pdo = \App\Core\DatabaseManager::getConnection();
$stmt = $pdo->query('SELECT 1');
$stmt->fetch();
} catch (\Exception $e) {
$this->triggerAlert('errors', 'database_connection', [
'error' => $e->getMessage(),
'message' => 'Falha na conectividade da base de dados'
]);
}
}
/**
* Obter uso de disco
*/
private function getDiskUsage(): float
{
$path = __DIR__ . '/../../';
$total = disk_total_space($path);
$free = disk_free_space($path);
return round((($total - $free) / $total) * 100, 2);
}
/**
* Obter contagem de tentativas de login falhadas
*/
private function getFailedLoginsCount(string $ip): int
{
// Implementação simplificada - em produção usar Redis ou base de dados
$cacheFile = __DIR__ . '/../../storage/cache/failed_logins.json';
if (file_exists($cacheFile)) {
$data = json_decode(file_get_contents($cacheFile), true);
return $data[$ip] ?? 0;
}
return 0;
}
/**
* Obter contagem de IPs suspeitos
*/
private function getSuspiciousIPCount(string $ip): int
{
// Implementação simplificada
$cacheFile = __DIR__ . '/../../storage/cache/suspicious_ips.json';
if (file_exists($cacheFile)) {
$data = json_decode(file_get_contents($cacheFile), true);
return $data[$ip] ?? 0;
}
return 0;
}
/**
* Obter contagem de erros
*/
private function getErrorCount(string $errorType): int
{
// Implementação simplificada
$cacheFile = __DIR__ . '/../../storage/cache/error_counts.json';
if (file_exists($cacheFile)) {
$data = json_decode(file_get_contents($cacheFile), true);
return $data[$errorType] ?? 0;
}
return 0;
}
/**
* Criar alerta manual
*/
public function createAlert(string $type, string $title, string $message, string $priority = 'medium', array $context = []): void
{
$alert = [
'id' => (string) new \Visus\Cuid2\Cuid2(),
'category' => 'manual',
'type' => $type,
'title' => $title,
'message' => $message,
'priority' => $priority,
'timestamp' => time(),
'data' => $context,
'context' => $context
];
// Log do alerta
$this->logger->alert($message, $alert);
// Guardar no histórico
$alertKey = "manual_{$type}";
$this->alertHistory[$alertKey] = $alert;
// Enviar notificação se configurado
if ($this->config['email']['enabled']) {
$this->sendEmailAlert($alert);
}
// Guardar alerta em ficheiro
$this->saveAlert($alert);
}
/**
* Disparar alerta
*/
private function triggerAlert(string $category, string $type, array $data): void
{
$alertKey = "{$category}_{$type}";
$cooldown = $this->config['cooldown'][$category] ?? 300;
// Verificar cooldown
if ($this->isInCooldown($alertKey, $cooldown)) {
return;
}
$alert = [
'id' => (string) new \Visus\Cuid2\Cuid2(),
'category' => $category,
'type' => $type,
'timestamp' => time(),
'data' => $data,
'message' => $data['message'] ?? 'Alerta disparado'
];
// Log do alerta
$this->logger->alert($alert['message'], $alert);
// Guardar no histórico
$this->alertHistory[$alertKey] = $alert;
// Enviar notificação se configurado
if ($this->config['email']['enabled']) {
$this->sendEmailAlert($alert);
}
// Guardar alerta em ficheiro
$this->saveAlert($alert);
}
/**
* Verificar se está em cooldown
*/
private function isInCooldown(string $alertKey, int $cooldown): bool
{
if (!isset($this->alertHistory[$alertKey])) {
return false;
}
$lastAlert = $this->alertHistory[$alertKey];
return (time() - $lastAlert['timestamp']) < $cooldown;
}
/**
* Enviar alerta por email
*/
private function sendEmailAlert(array $alert): void
{
$to = $this->config['email']['to'];
$from = $this->config['email']['from'];
$subject = "🚨 Alerta BitReport CRM - {$alert['category']}";
$message = "
<h2>🚨 Alerta do Sistema BitReport CRM</h2>
<p><strong>Categoria:</strong> {$alert['category']}</p>
<p><strong>Tipo:</strong> {$alert['type']}</p>
<p><strong>Mensagem:</strong> {$alert['message']}</p>
<p><strong>Data/Hora:</strong> " . date('Y-m-d H:i:s', $alert['timestamp']) . "</p>
<h3>Detalhes:</h3>
<pre>" . json_encode($alert['data'], JSON_PRETTY_PRINT) . "</pre>
<hr>
<p><em>Este é um alerta automático do sistema BitReport CRM.</em></p>
";
$headers = [
'MIME-Version: 1.0',
'Content-type: text/html; charset=utf-8',
'From: ' . $from,
'Reply-To: ' . $from,
'X-Mailer: PHP/' . phpversion()
];
mail($to, $subject, $message, implode("\r\n", $headers));
}
/**
* Guardar alerta em ficheiro
*/
private function saveAlert(array $alert): void
{
$alertsFile = __DIR__ . '/../../storage/logs/alerts.json';
$alerts = [];
if (file_exists($alertsFile)) {
$alerts = json_decode(file_get_contents($alertsFile), true) ?? [];
}
$alerts[] = $alert;
// Manter apenas últimos 100 alertas
if (count($alerts) > 100) {
$alerts = array_slice($alerts, -100);
}
file_put_contents($alertsFile, json_encode($alerts, JSON_PRETTY_PRINT));
}
/**
* Obter histórico de alertas
*/
public function getAlertHistory(): array
{
$alertsFile = __DIR__ . '/../../storage/logs/alerts.json';
if (file_exists($alertsFile)) {
return json_decode(file_get_contents($alertsFile), true) ?? [];
}
return [];
}
/**
* Obter estatísticas de alertas
*/
public function getAlertStats(): array
{
$alerts = $this->getAlertHistory();
$stats = [
'total' => count($alerts),
'by_category' => [],
'by_type' => [],
'recent' => []
];
foreach ($alerts as $alert) {
$category = $alert['category'];
$type = $alert['type'];
$stats['by_category'][$category] = ($stats['by_category'][$category] ?? 0) + 1;
$stats['by_type'][$type] = ($stats['by_type'][$type] ?? 0) + 1;
}
// Últimos 10 alertas
$stats['recent'] = array_slice($alerts, -10);
return $stats;
}
/**
* Limpar alertas antigos
*/
public function cleanupAlerts(int $daysToKeep = 30): int
{
$alerts = $this->getAlertHistory();
$cutoff = time() - ($daysToKeep * 24 * 60 * 60);
$originalCount = count($alerts);
$alerts = array_filter($alerts, function($alert) use ($cutoff) {
return $alert['timestamp'] > $cutoff;
});
$alertsFile = __DIR__ . '/../../storage/logs/alerts.json';
file_put_contents($alertsFile, json_encode(array_values($alerts), JSON_PRETTY_PRINT));
return $originalCount - count($alerts);
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace App\Core;
use App\Core\View;
class AppConfig
{
// Branding dinâmico
private static function getBranding(): array
{
return \App\Core\Branding::get();
}
public static function getLogoLight(): string
{
$branding = self::getBranding();
return View::asset($branding['logo_light'] ?? '/assets/images/bitreport-logo-light.png');
}
public static function getLogoDark(): string
{
$branding = self::getBranding();
return View::asset($branding['logo_dark'] ?? '/assets/images/bitreport-logo-dark.png');
}
public static function getLogo(): string
{
$branding = self::getBranding();
return View::asset($branding['logo_url'] ?? '/assets/images/bitreport-logo.png');
}
public static function getLogoSm(): string
{
$branding = self::getBranding();
return View::asset($branding['logo_url'] ?? '/assets/images/bitreport-logo-sm.png');
}
public static function getBrandName(): string
{
$branding = self::getBranding();
return $branding['company_name'] ?? 'BitReport';
}
public static function getFavicon(): string
{
$branding = self::getBranding();
return View::asset($branding['favicon_url'] ?? '/assets/images/favicon.ico');
}
public static function getCompanyName(): string
{
$branding = self::getBranding();
return $branding['company_name'] ?? 'BitReport';
}
public static function getCompanyUrl(): string
{
$branding = self::getBranding();
return $branding['company_url'] ?? 'https://bitreport.pt';
}
public static function getSupportEmail(): string
{
$branding = self::getBranding();
return $branding['support_email'] ?? '[email protected]';
}
public static function getDefaultLanguage(): string
{
return 'pt';
}
public static function getSupportedLanguages(): array
{
return ['pt', 'en', 'es', 'fr', 'it', 'de'];
}
public static function getThemeDefault(): string
{
return 'light';
}
public static function getCopyright(): string
{
$branding = self::getBranding();
$companyName = $branding['company_name'] ?? 'BitReport';
return '© ' . date('Y') . ' ' . $companyName . '. All rights reserved.';
}
public static function getUserAvatar(): string
{
return View::asset('/assets/images/users/avatar-1.jpg');
}
public static function getUserName(): string
{
return 'Admin';
}
public static function getUserTitle(): string
{
return 'Administrator';
}
}
+384
View File
@@ -0,0 +1,384 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* AssetManager - Modular Asset Management System
*
* Automatically discovers and manages CSS/JS assets from modules
* Similar to widget system but for stylesheets and scripts
*/
class AssetManager
{
private static ?AssetManager $instance = null;
private array $registeredAssets = [];
private array $loadedModules = [];
private array $compiledAssets = [];
private function __construct() {}
public static function getInstance(): AssetManager
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Register CSS/JS assets for a module
*/
public function registerModuleAssets(string $moduleName, array $assets): void
{
$this->registeredAssets[$moduleName] = array_merge(
$this->registeredAssets[$moduleName] ?? [],
$assets
);
}
/**
* Auto-discover assets from all active modules
*/
public function discoverModuleAssets(): void
{
$modulesPath = PathManager::getModulesPath();
if (!is_dir($modulesPath)) {
return;
}
// Get current client ID and module config
$clientId = \App\Core\Branding::getClientId();
$moduleConfig = \App\Core\ModuleConfig::getInstance();
$modules = scandir($modulesPath);
foreach ($modules as $module) {
if ($module === '.' || $module === '..') {
continue;
}
// Check if module is active for current client
if (!$moduleConfig->isModuleActive($module, $clientId)) {
continue;
}
$modulePath = $modulesPath . DIRECTORY_SEPARATOR . $module;
if (!is_dir($modulePath)) {
continue;
}
// Check if module has assets.php file
$assetsFile = $modulePath . DIRECTORY_SEPARATOR . 'assets.php';
if (file_exists($assetsFile)) {
try {
require_once $assetsFile;
} catch (\Exception $e) {
error_log("Error loading assets for module {$module}: " . $e->getMessage());
}
}
// Auto-discover CSS/SCSS files in assets directory
$this->autoDiscoverAssets($module, $modulePath);
}
}
/**
* Auto-discover CSS/SCSS files in module's assets directory
*/
private function autoDiscoverAssets(string $moduleName, string $modulePath): void
{
$assetsPath = $modulePath . DIRECTORY_SEPARATOR . 'assets';
if (!is_dir($assetsPath)) {
return;
}
$discoveredAssets = [];
// Look for CSS files
$cssFiles = glob($assetsPath . '/*.css');
foreach ($cssFiles as $cssFile) {
$filename = basename($cssFile);
$discoveredAssets['css'][] = [
'name' => $filename,
'path' => $cssFile,
'url' => $this->getAssetUrl($moduleName, 'css', $filename),
'priority' => 10, // Default priority
];
}
// Look for SCSS files
$scssFiles = glob($assetsPath . '/*.scss');
foreach ($scssFiles as $scssFile) {
$filename = basename($scssFile);
$discoveredAssets['scss'][] = [
'name' => $filename,
'path' => $scssFile,
'url' => $this->getCompiledAssetUrl($moduleName, 'css', str_replace('.scss', '.css', $filename)),
'priority' => 10,
'compile' => true,
];
}
// Look for JS files
$jsFiles = glob($assetsPath . '/*.js');
foreach ($jsFiles as $jsFile) {
$filename = basename($jsFile);
$discoveredAssets['js'][] = [
'name' => $filename,
'path' => $jsFile,
'url' => $this->getAssetUrl($moduleName, 'js', $filename),
'priority' => 10,
];
}
if (!empty($discoveredAssets)) {
$this->registerModuleAssets($moduleName, $discoveredAssets);
}
}
/**
* Get asset URL for a module
*/
private function getAssetUrl(string $moduleName, string $type, string $filename): string
{
return "/assets/modules/{$moduleName}/{$type}/{$filename}";
}
/**
* Get compiled asset URL
*/
private function getCompiledAssetUrl(string $moduleName, string $type, string $filename): string
{
return "/assets/compiled/modules/{$moduleName}/{$type}/{$filename}";
}
/**
* Load assets for specific modules
*/
public function loadModuleAssets(array $moduleNames): array
{
$assets = [
'css' => [],
'js' => [],
];
foreach ($moduleNames as $moduleName) {
if (isset($this->registeredAssets[$moduleName])) {
$moduleAssets = $this->registeredAssets[$moduleName];
// Add CSS assets
if (isset($moduleAssets['css'])) {
$assets['css'] = array_merge($assets['css'], $moduleAssets['css']);
}
if (isset($moduleAssets['scss'])) {
// SCSS files that should be compiled to CSS
$assets['css'] = array_merge($assets['css'], $moduleAssets['scss']);
}
// Add JS assets
if (isset($moduleAssets['js'])) {
$assets['js'] = array_merge($assets['js'], $moduleAssets['js']);
}
$this->loadedModules[] = $moduleName;
}
}
// Sort by priority
usort($assets['css'], function($a, $b) {
return ($a['priority'] ?? 10) <=> ($b['priority'] ?? 10);
});
usort($assets['js'], function($a, $b) {
return ($a['priority'] ?? 10) <=> ($b['priority'] ?? 10);
});
return $assets;
}
/**
* Get CSS links HTML for specific modules
*/
public function getCssLinks(array $moduleNames): string
{
$assets = $this->loadModuleAssets($moduleNames);
$html = '';
foreach ($assets['css'] as $css) {
$url = $css['url'];
$media = $css['media'] ?? 'all';
$html .= "<link rel=\"stylesheet\" href=\"{$url}\" media=\"{$media}\">\n";
}
return $html;
}
/**
* Get JS script tags HTML for specific modules
*/
public function getJsScripts(array $moduleNames): string
{
$assets = $this->loadModuleAssets($moduleNames);
$html = '';
foreach ($assets['js'] as $js) {
$url = $js['url'];
$defer = isset($js['defer']) && $js['defer'] ? ' defer' : '';
$async = isset($js['async']) && $js['async'] ? ' async' : '';
$html .= "<script src=\"{$url}\"{$defer}{$async}></script>\n";
}
return $html;
}
/**
* Get currently active modules (from current request)
*/
public function getActiveModules(): array
{
// Get active modules from current route/request
$activeModules = [];
// Check current URL to determine active modules
$requestUri = $_SERVER['REQUEST_URI'] ?? '/';
$pathParts = explode('/', trim($requestUri, '/'));
// Map URL patterns to modules
$moduleMapping = [
'crm' => ['Crm'],
'advertising' => ['Advertising'],
'error-monitoring' => ['ErrorMonitoring'],
'analytics' => ['Analytics'],
'projects' => ['Projects'],
'users' => ['Users'],
'dashboard' => ['Dashboard', 'Crm', 'Advertising', 'Analytics'], // Dashboard uses multiple modules
'api' => $this->getApiModules($pathParts),
];
// Always include Core module
$activeModules[] = 'Core';
// Determine modules based on URL
if (!empty($pathParts[0]) && isset($moduleMapping[$pathParts[0]])) {
$activeModules = array_merge($activeModules, $moduleMapping[$pathParts[0]]);
} else {
// Default modules for homepage
$activeModules = array_merge($activeModules, ['Dashboard', 'Crm', 'Advertising']);
}
return array_unique($activeModules);
}
/**
* Get modules for API requests
*/
private function getApiModules(array $pathParts): array
{
if (count($pathParts) < 2) {
return [];
}
$apiModuleMapping = [
'crm' => ['Crm'],
'advertising' => ['Advertising'],
'error-monitoring' => ['ErrorMonitoring'],
'analytics' => ['Analytics'],
'dashboard' => ['Dashboard'],
];
return $apiModuleMapping[$pathParts[1]] ?? [];
}
/**
* Compile SCSS files to CSS
*/
public function compileScssAssets(): bool
{
$compiled = 0;
$errors = [];
foreach ($this->registeredAssets as $moduleName => $assets) {
if (!isset($assets['scss'])) {
continue;
}
foreach ($assets['scss'] as $scss) {
if (!isset($scss['compile']) || !$scss['compile']) {
continue;
}
try {
$result = $this->compileScssFile($scss['path'], $moduleName);
if ($result) {
$compiled++;
}
} catch (\Exception $e) {
$errors[] = "Error compiling {$scss['path']}: " . $e->getMessage();
}
}
}
if (!empty($errors)) {
error_log("SCSS compilation errors: " . implode(', ', $errors));
}
return empty($errors);
}
/**
* Compile individual SCSS file
*/
private function compileScssFile(string $scssPath, string $moduleName): bool
{
$outputDir = PathManager::getPublicPath() . '/assets/compiled/modules/' . $moduleName . '/css';
if (!is_dir($outputDir)) {
mkdir($outputDir, 0755, true);
}
$filename = basename($scssPath, '.scss') . '.css';
$outputPath = $outputDir . '/' . $filename;
// Use sass command to compile
$command = "npx sass --no-source-map \"{$scssPath}\" \"{$outputPath}\"";
$result = shell_exec($command . ' 2>&1');
if (!file_exists($outputPath)) {
throw new \Exception("SCSS compilation failed: {$result}");
}
return true;
}
/**
* Get all registered assets for debugging
*/
public function getRegisteredAssets(): array
{
return $this->registeredAssets;
}
/**
* Clear registered assets (for testing)
*/
public function clearAssets(): void
{
$this->registeredAssets = [];
$this->loadedModules = [];
}
/**
* Initialize asset manager and discover all module assets
*/
public static function initialize(): void
{
$manager = self::getInstance();
$manager->discoverModuleAssets();
}
}
+222
View File
@@ -0,0 +1,222 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Classe utilitária para gerar paths de assets
* Garante consistência e facilita mudanças futuras
*/
class AssetPath
{
/**
* Base path para assets
*/
private static string $basePath = '/assets';
/**
* Gerar path para CSS
*/
public static function css(string $file): string
{
return self::$basePath . '/css/' . ltrim($file, '/');
}
/**
* Gerar path para JavaScript
*/
public static function js(string $file): string
{
return self::$basePath . '/js/' . ltrim($file, '/');
}
/**
* Gerar path para imagens
*/
public static function image(string $file): string
{
return self::$basePath . '/images/' . ltrim($file, '/');
}
/**
* Gerar path para fontes
*/
public static function font(string $file): string
{
return self::$basePath . '/fonts/' . ltrim($file, '/');
}
/**
* Gerar path para libs (bibliotecas externas)
*/
public static function lib(string $file): string
{
return self::$basePath . '/libs/' . ltrim($file, '/');
}
/**
* Gerar path para JSON
*/
public static function json(string $file): string
{
return self::$basePath . '/json/' . ltrim($file, '/');
}
/**
* Gerar path para lordicon
*/
public static function lordicon(string $file): string
{
return self::$basePath . '/lordicon/' . ltrim($file, '/');
}
/**
* Gerar path para lang (traduções)
*/
public static function lang(string $file): string
{
return self::$basePath . '/lang/' . ltrim($file, '/');
}
/**
* Gerar path para SCSS
*/
public static function scss(string $file): string
{
return self::$basePath . '/scss/' . ltrim($file, '/');
}
/**
* Gerar path genérico
*/
public static function path(string $path): string
{
return self::$basePath . '/' . ltrim($path, '/');
}
/**
* Definir base path (útil para testes ou configurações especiais)
*/
public static function setBasePath(string $path): void
{
self::$basePath = rtrim($path, '/');
}
/**
* Obter base path atual
*/
public static function getBasePath(): string
{
return self::$basePath;
}
/**
* Verificar se asset existe
*/
public static function exists(string $path): bool
{
$fullPath = $_SERVER['DOCUMENT_ROOT'] . self::path($path);
return file_exists($fullPath);
}
/**
* Obter timestamp do asset para cache busting
*/
public static function version(string $path): string
{
$fullPath = $_SERVER['DOCUMENT_ROOT'] . self::path($path);
if (file_exists($fullPath)) {
return '?v=' . filemtime($fullPath);
}
return '';
}
/**
* Gerar path com version para cache busting
*/
public static function versioned(string $path): string
{
return self::path($path) . self::version($path);
}
/**
* Gerar path para bundle principal
*/
public static function bundle(): string
{
return self::js('app.bundle.js') . self::version('js/app.bundle.js');
}
/**
* Gerar path para CSS principal
*/
public static function stylesheet(): string
{
return self::css('app.bundle.css') . self::version('css/app.bundle.css');
}
/**
* Get the latest JS bundle (app.*.js ou public.*.js), com cache estática.
* @param string $type 'app' ou 'public'
* @return string Caminho relativo para o bundle
*/
public static function getLatestJsBundle(string $type = 'app'): string
{
static $cache = [];
if (isset($cache[$type])) {
return $cache[$type];
}
$jsDir = defined('PUBLIC_PATH') ? PUBLIC_PATH . '/assets/js/' : $_SERVER['DOCUMENT_ROOT'] . '/assets/js/';
$pattern = $jsDir . $type . '.*.js';
$files = glob($pattern);
if (!empty($files)) {
usort($files, function($a, $b) { return filemtime($b) - filemtime($a); });
$cache[$type] = '/assets/js/' . basename($files[0]);
return $cache[$type];
}
// Fallbacks
if ($type === 'public' && file_exists($jsDir . 'public.bundle.js')) {
$cache[$type] = '/assets/js/public.bundle.js';
return $cache[$type];
}
if (file_exists($jsDir . 'app.bundle.js')) {
$cache[$type] = '/assets/js/app.bundle.js';
return $cache[$type];
}
$cache[$type] = '';
return '';
}
/**
* Get the vendor bundle path (vendor.*.js)
* @return string Caminho relativo para o vendor bundle
*/
public static function getVendorBundle(): string
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$jsDir = defined('PUBLIC_PATH') ? PUBLIC_PATH . '/assets/js/' : $_SERVER['DOCUMENT_ROOT'] . '/assets/js/';
$pattern = $jsDir . 'vendor.*.js';
$files = glob($pattern);
if (!empty($files)) {
usort($files, function($a, $b) { return filemtime($b) - filemtime($a); });
$cache = '/assets/js/' . basename($files[0]);
return $cache;
}
// Fallback
if (file_exists($jsDir . 'vendor.bundle.js')) {
$cache = '/assets/js/vendor.bundle.js';
return $cache;
}
$cache = '';
return '';
}
}
+336
View File
@@ -0,0 +1,336 @@
<?php
declare(strict_types=1);
namespace App\Core;
use App\Modules\Users\Models\UserModel;
use PDO;
class Auth
{
private const REMEMBER_COOKIE_NAME = 'bitreport_remember';
private const REMEMBER_COOKIE_DURATION = 30 * 24 * 60 * 60; // 30 days
/**
* Attempt to log the user in.
*
* @param string $email
* @param string $password
* @param bool $rememberMe
* @return bool
*/
public static function login(string $email, string $password, bool $rememberMe = false): bool
{
try {
$db = DatabaseManager::getInstance()->getConnection();
$stmt = $db->prepare("SELECT * FROM users WHERE email = ? AND is_active = 1");
$stmt->execute([$email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
self::createSession($user);
return true;
}
return false;
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'login', 'email' => $email]);
return false;
}
}
/**
* Log the user out.
*/
public static function logout(): void
{
$db = DatabaseManager::getInstance()->getConnection();
// Clear remember token if exists
if (isset($_COOKIE['remember_token'])) {
$stmt = $db->prepare("UPDATE users SET remember_token = NULL WHERE remember_token = ?");
$stmt->execute([$_COOKIE['remember_token']]);
setcookie('remember_token', '', time() - 3600, '/');
}
// Destroy session
session_destroy();
}
/**
* Check if the user is authenticated.
*/
public static function check(): bool
{
// Development hook: Auto-login as Pedro Alves on localhost for testing
if (self::isDevelopmentMode() && !self::isAuthenticated()) {
self::forceLoginAsPedro();
}
// First check session
if (isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'] === true) {
return true;
}
// If no session, check remember me cookie
return self::loginFromRememberCookie();
}
/**
* Get the authenticated user's ID.
*
* @return int|null
*/
public static function id(): ?int
{
return $_SESSION['user_id'] ?? null;
}
/**
* Get the authenticated user's data.
*
* @return array|false
*/
public static function user()
{
if (!self::check()) {
return false;
}
$userModel = new UserModel();
return $userModel->find(self::id());
}
/**
* Set remember me cookie
*/
private static function setRememberCookie(int $userId): void
{
$token = bin2hex(random_bytes(32)); // Generate secure random token
$expires = time() + self::REMEMBER_COOKIE_DURATION;
// Store token in database (you might want to create a remember_tokens table)
$db = DatabaseManager::getInstance()->getConnection();
$stmt = $db->prepare("UPDATE users SET remember_token = :token, remember_token_expires = :expires WHERE id = :user_id");
$stmt->execute([
'token' => $token,
'expires' => date('Y-m-d H:i:s', $expires),
'user_id' => $userId
]);
// Set cookie
setcookie(
self::REMEMBER_COOKIE_NAME,
$token,
$expires,
'/',
'',
true, // secure
true // httponly
);
}
/**
* Clear remember me cookie
*/
private static function clearRememberCookie(): void
{
// Clear from database
if (isset($_SESSION['user_id'])) {
$db = DatabaseManager::getInstance()->getConnection();
$stmt = $db->prepare("UPDATE users SET remember_token = NULL, remember_token_expires = NULL WHERE id = :user_id");
$stmt->execute(['user_id' => $_SESSION['user_id']]);
}
// Clear cookie
setcookie(self::REMEMBER_COOKIE_NAME, '', time() - 3600, '/');
}
/**
* Attempt to login from remember me cookie
*/
private static function loginFromRememberCookie(): bool
{
if (!isset($_COOKIE[self::REMEMBER_COOKIE_NAME])) {
return false;
}
$token = $_COOKIE[self::REMEMBER_COOKIE_NAME];
$db = DatabaseManager::getInstance()->getConnection();
$stmt = $db->prepare("SELECT id FROM users WHERE remember_token = :token AND remember_token_expires > NOW() AND is_active = 1");
if ($stmt->execute(['token' => $token])) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
// Auto-login successful
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_logged_in'] = true;
return true;
}
}
// Invalid or expired token, clear cookie
setcookie(self::REMEMBER_COOKIE_NAME, '', time() - 3600, '/');
return false;
}
/**
* Check if we're in development mode
*/
private static function isDevelopmentMode(): bool
{
$host = $_SERVER['HTTP_HOST'] ?? '';
return $host === 'localhost:8888' || $host === '127.0.0.1:8888';
}
/**
* Check if user is currently authenticated
*/
private static function isAuthenticated(): bool
{
return isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'] === true;
}
/**
* Force login as Pedro Alves for development testing
*/
private static function forceLoginAsPedro(): void
{
$db = DatabaseManager::getInstance()->getConnection();
// Get Pedro Alves user ID and role
$stmt = $db->prepare("SELECT id, role FROM users WHERE email = :email AND is_active = 1");
if ($stmt->execute(['email' => '[email protected]'])) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
// Force login
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_logged_in'] = true;
$_SESSION['user_role'] = $user['role'] ?? 'admin';
// Log for debugging
error_log("[DEV] Auto-logged in as Pedro Alves (ID: {$user['id']}) for testing");
}
}
}
private static function createSession(array $user): void
{
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['email'] = $user['email'];
$_SESSION['role'] = $user['role'];
$_SESSION['logged_in_at'] = time();
$_SESSION['user_logged_in'] = true;
}
/**
* Check if user has admin role
*/
public static function isAdmin(): bool
{
if (!self::check()) {
return false;
}
$user = self::user();
return $user && ($user['role'] === 'admin' || $user['role'] === 'super_admin');
}
/**
* Check if user has specific role
*/
public static function hasRole(string $role): bool
{
if (!self::check()) {
return false;
}
$user = self::user();
return $user && $user['role'] === $role;
}
/**
* Check if user owns a resource (by user_id field)
*/
public static function ownsResource(array $resource): bool
{
if (!self::check()) {
return false;
}
$userId = self::id();
return isset($resource['user_id']) && $resource['user_id'] == $userId;
}
/**
* Check if user can access resource (owner or admin)
*/
public static function canAccess(array $resource): bool
{
return self::isAdmin() || self::ownsResource($resource);
}
/**
* Check if user can modify resource (owner or admin)
*/
public static function canModify(array $resource): bool
{
return self::isAdmin() || self::ownsResource($resource);
}
/**
* Check if user can delete resource (owner or admin)
*/
public static function canDelete(array $resource): bool
{
return self::isAdmin() || self::ownsResource($resource);
}
/**
* Require authentication or return 401
*/
public static function requireAuth(): void
{
if (!self::check()) {
http_response_code(401);
header('Content-Type: application/json');
echo json_encode(['error' => 'Unauthorized', 'message' => 'Authentication required']);
exit;
}
}
/**
* Require admin role or return 403
*/
public static function requireAdmin(): void
{
self::requireAuth();
if (!self::isAdmin()) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['error' => 'Forbidden', 'message' => 'Admin access required']);
exit;
}
}
/**
* Require resource ownership or admin role
*/
public static function requireOwnership(array $resource): void
{
self::requireAuth();
if (!self::canModify($resource)) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['error' => 'Forbidden', 'message' => 'Resource access denied']);
exit;
}
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace App\Core;
class AuthMiddleware
{
/**
* Check if user is authenticated. If not, redirect to login page.
*/
public static function requireAuth(): void
{
if (!Auth::check()) {
header('Location: /login');
exit();
}
}
/**
* Check if user has a specific role.
*/
public static function requireRole(string $role): void
{
self::requireAuth();
$user = Auth::user();
if (!$user || $user['role'] !== $role) {
// Or redirect to a "403 Forbidden" page
header('Location: /');
exit;
}
}
/**
* Check if user has admin role.
*/
public static function requireAdmin(): void
{
self::requireRole('admin');
}
/**
* If user is already logged in, redirect them from login/register pages.
*/
public static function redirectIfAuthenticated(): void
{
if (Auth::check()) {
header('Location: /apps/users/profile'); // Redirect to profile or dashboard
exit();
}
}
public function requireGuest(): void
{
if (Auth::check()) {
header('Location: /apps/users/profile'); // Redirect to profile or dashboard
exit();
}
}
}
+641
View File
@@ -0,0 +1,641 @@
<?php
declare(strict_types=1);
namespace App\Core;
use App\Core\Auth;
use App\Core\View;
use App\Core\ErrorReporter;
use App\Core\InputSanitizer;
use App\Core\Validator;
use App\Core\ServiceContainer;
use App\Core\ValidatorFactory;
/**
* BaseController - Controller base para todos os controllers
* Fornece funcionalidades comuns e métodos utilitários
*/
abstract class BaseController
{
protected array $data = [];
protected ?Validator $validator = null;
protected string $moduleName;
protected ServiceContainer $container;
/**
* Construtor do BaseController
*/
public function __construct(string $moduleName = '')
{
$this->moduleName = $moduleName;
$this->container = ServiceContainer::getInstance();
}
/**
* Resolver um serviço do módulo
*/
protected function resolveModuleService(string $serviceName)
{
if (empty($this->moduleName)) {
throw new \InvalidArgumentException('Module name not set in controller');
}
// Tentar resolver como "Module:ServiceName"
try {
return $this->container->resolve($this->moduleName . ':' . $serviceName);
} catch (\InvalidArgumentException $e) {
// Se falhar, tentar resolver diretamente
return $this->container->resolve($serviceName);
}
}
/**
* Resolver um serviço global
*/
protected function resolve(string $serviceName)
{
return $this->container->resolve($serviceName);
}
/**
* Renderizar view
*/
protected function render(string $view, array $data = []): void
{
$this->data = array_merge($this->data, $data);
View::render($view, $this->data);
}
/**
* Resposta JSON
*/
protected function jsonResponse(array $data, int $statusCode = 200): void
{
// Clean any previous output
if (ob_get_level()) {
ob_clean();
}
// Only set headers if they haven't been sent yet
if (!headers_sent()) {
http_response_code($statusCode);
header('Content-Type: application/json');
}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit; // Ensure no further output
}
/**
* Resposta de erro padronizada
*/
protected function errorResponse(string $message, int $statusCode = 400, array $errors = []): void
{
$response = [
'success' => false,
'message' => $message
];
if (!empty($errors)) {
$response['errors'] = $errors;
}
$this->jsonResponse($response, $statusCode);
}
/**
* Resposta de sucesso padronizada
*/
protected function successResponse(array $data = [], string $message = 'Success'): void
{
$response = [
'success' => true,
'message' => $message
];
if (!empty($data)) {
$response['data'] = $data;
}
$this->jsonResponse($response);
}
/**
* Validar se o utilizador está autenticado
*/
/**
* Detectar se é uma página pública baseado no contexto
*/
protected function isPublicPage(): bool
{
// Detectar por URL patterns
$currentUrl = $_SERVER['REQUEST_URI'] ?? '';
$publicPatterns = [
'/public/',
'/api/ecommerce/products',
'/api/ecommerce/filter-options',
'/api/error-monitoring/'
];
foreach ($publicPatterns as $pattern) {
if (strpos($currentUrl, $pattern) !== false) {
return true;
}
}
// Detectar por layout/tema
$layout = $_GET['layout'] ?? $_POST['layout'] ?? '';
if ($layout === 'public' || $layout === 'public-blank') {
return true;
}
// Detectar por referer se for API
if (strpos($currentUrl, '/api/') !== false) {
$referer = $_SERVER['HTTP_REFERER'] ?? '';
if (strpos($referer, '/public/') !== false) {
return true;
}
}
return false;
}
protected function requireAuth(): void
{
// Se for página pública, não requer autenticação
if ($this->isPublicPage()) {
return;
}
if (!Auth::check()) {
$this->errorResponse('Authentication required', 401);
}
}
/**
* Obter dados sanitizados do request
*/
protected function getSanitizedInput(): array
{
return InputSanitizer::all('POST');
}
/**
* Obter um parâmetro específico sanitizado
*/
protected function getSanitizedParam(string $key, $default = null)
{
$input = $this->getSanitizedInput();
return $input[$key] ?? $default;
}
/**
* Log de atividade
*/
protected function logActivity(string $action, array $context = []): void
{
ErrorReporter::report(new \Exception("Activity: $action"), $context);
}
// =============================================================================
// MÉTODOS DE VALIDAÇÃO AUTOMÁTICA
// =============================================================================
/**
* Validar dados com regras
*/
protected function validate(array $data, array $rules, array $messages = []): bool
{
$this->validator = Validator::make($data, $rules, $messages);
return $this->validator->validate();
}
/**
* Validar dados automaticamente usando ValidatorFactory
*/
protected function validateAuto(array $data, string $type): array
{
return ValidatorFactory::validate($data, $type);
}
/**
* Validar e sanitizar dados automaticamente
*/
protected function validateAndSanitizeAuto(array $data, string $type): array
{
return ValidatorFactory::validateAndSanitize($data, $type);
}
/**
* Validar POST automaticamente
*/
protected function validatePostAuto(string $type): array
{
$data = $this->getSanitizedInput();
return $this->validateAuto($data, $type);
}
/**
* Validar POST e retornar resposta de erro se falhar
*/
protected function validatePostAutoOrFail(string $type): array
{
$data = $this->getSanitizedInput();
$result = $this->validateAndSanitizeAuto($data, $type);
if (!$result['success']) {
$this->errorResponse(
$result['first_error'] ?? 'Validation failed',
422,
$result['errors']
);
}
return $result;
}
/**
* Validar dados sanitizados do POST
*/
protected function validatePost(array $rules, array $messages = []): bool
{
$data = $this->getSanitizedInput();
return $this->validate($data, $rules, $messages);
}
/**
* Validar dados sanitizados do GET
*/
protected function validateGet(array $rules, array $messages = []): bool
{
$data = InputSanitizer::all('GET');
return $this->validate($data, $rules, $messages);
}
/**
* Validar e retornar resposta de erro se falhar
*/
protected function validateOrFail(array $data, array $rules, array $messages = []): bool
{
if (!$this->validate($data, $rules, $messages)) {
$this->validationErrorResponse();
return false;
}
return true;
}
/**
* Validar POST e retornar resposta de erro se falhar
*/
protected function validatePostOrFail(array $rules, array $messages = []): bool
{
if (!$this->validatePost($rules, $messages)) {
$this->validationErrorResponse();
return false;
}
return true;
}
/**
* Validar GET e retornar resposta de erro se falhar
*/
protected function validateGetOrFail(array $rules, array $messages = []): bool
{
if (!$this->validateGet($rules, $messages)) {
$this->validationErrorResponse();
return false;
}
return true;
}
/**
* Resposta de erro de validação
*/
protected function validationErrorResponse(): void
{
if ($this->validator) {
$errors = $this->validator->getErrors();
$firstError = $this->validator->getFirstError();
$this->errorResponse(
$firstError ?? 'Validation failed',
422,
$errors
);
} else {
$this->errorResponse('Validation failed', 422);
}
}
/**
* Obter erros de validação
*/
protected function getValidationErrors(): array
{
return $this->validator ? $this->validator->getErrors() : [];
}
/**
* Obter primeiro erro de validação
*/
protected function getFirstValidationError(): ?string
{
return $this->validator ? $this->validator->getFirstError() : null;
}
/**
* Verificar se campo tem erro de validação
*/
protected function hasValidationError(string $field): bool
{
return $this->validator ? $this->validator->hasError($field) : false;
}
/**
* Obter erros de um campo específico
*/
protected function getFieldValidationErrors(string $field): array
{
return $this->validator ? $this->validator->getFieldErrors($field) : [];
}
// =============================================================================
// REGRAS DE VALIDAÇÃO PRÉ-DEFINIDAS
// =============================================================================
/**
* Regras para criação de utilizador
*/
protected function getUserCreateRules(): array
{
return [
'first_name' => 'required|min:2|max:50|alpha',
'last_name' => 'required|min:2|max:50|alpha',
'email' => 'required|email|max:100',
'username' => 'required|min:3|max:20|alphanumeric',
'password' => 'required|min:8|strong_password',
'password_confirmation' => 'required|confirmed',
'role' => 'required|in:admin,user,manager'
];
}
/**
* Regras para atualização de utilizador
*/
protected function getUserUpdateRules(): array
{
return [
'first_name' => 'required|min:2|max:50|alpha',
'last_name' => 'required|min:2|max:50|alpha',
'email' => 'required|email|max:100',
'phone' => 'nullable|phone|max:20',
'city' => 'nullable|max:100',
'country' => 'nullable|max:100',
'website' => 'nullable|url|max:255',
'job_title' => 'nullable|max:100',
'company_name' => 'nullable|max:100',
'description' => 'nullable|max:500'
];
}
/**
* Regras para criação de contacto
*/
protected function getContactCreateRules(): array
{
return [
'first_name' => 'required|min:2|max:50|alpha',
'last_name' => 'required|min:2|max:50|alpha',
'email' => 'required|email|max:100',
'phone' => 'nullable|phone|max:20',
'mobile' => 'nullable|phone|max:20',
'job_title' => 'nullable|max:100',
'company_id' => 'nullable|integer',
'website' => 'nullable|url|max:255',
'address' => 'nullable|max:255',
'city' => 'nullable|max:100',
'state' => 'nullable|max:100',
'country' => 'nullable|max:100',
'zip_code' => 'nullable|max:20',
'notes' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,lead,customer,prospect',
'source' => 'nullable|max:100'
];
}
/**
* Regras para criação de empresa
*/
protected function getCompanyCreateRules(): array
{
return [
'name' => 'required|min:2|max:255',
'email' => 'nullable|email|max:100',
'phone' => 'nullable|phone|max:20',
'website' => 'nullable|url|max:255',
'address' => 'nullable|max:255',
'city' => 'nullable|max:100',
'state' => 'nullable|max:100',
'country' => 'nullable|max:100',
'zip_code' => 'nullable|max:20',
'industry' => 'nullable|max:100',
'company_size' => 'nullable|in:1-10,11-50,51-200,201-500,501-1000,1000+',
'annual_revenue' => 'nullable|decimal',
'description' => 'nullable|max:1000',
'notes' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,prospect,customer,partner',
'source' => 'nullable|max:100'
];
}
/**
* Regras para criação de negócio
*/
protected function getDealCreateRules(): array
{
return [
'title' => 'required|min:3|max:255',
'description' => 'nullable|max:1000',
'value' => 'nullable|decimal|min_value:0',
'stage' => 'required|in:new,qualification,proposal,negotiation,closed_won,closed_lost',
'status' => 'required|in:open,closed',
'company_id' => 'nullable|integer',
'contact_id' => 'nullable|integer',
'expected_close_date' => 'nullable|date',
'probability' => 'nullable|integer|between:0,100',
'source' => 'nullable|max:100',
'notes' => 'nullable|max:1000'
];
}
/**
* Regras para criação de lead
*/
protected function getLeadCreateRules(): array
{
return [
'name' => 'required|min:2|max:255',
'email' => 'required|email|max:100',
'phone' => 'nullable|phone|max:20',
'company' => 'nullable|max:255',
'job_title' => 'nullable|max:100',
'source' => 'nullable|max:100',
'status' => 'required|in:new,contacted,qualified,converted,lost',
'score' => 'nullable|integer|between:1,10',
'notes' => 'nullable|max:1000',
'assigned_to' => 'nullable|integer'
];
}
/**
* Regras para criação de tarefa
*/
protected function getTaskCreateRules(): array
{
return [
'title' => 'required|min:3|max:255',
'description' => 'nullable|max:1000',
'due_date' => 'required|date',
'priority' => 'required|in:low,medium,high,urgent',
'status' => 'required|in:pending,in_progress,completed,cancelled',
'assigned_to' => 'nullable|integer',
'related_type' => 'nullable|in:contact,company,deal,lead',
'related_id' => 'nullable|integer',
'notes' => 'nullable|max:1000'
];
}
/**
* Regras para criação de campanha
*/
protected function getCampaignCreateRules(): array
{
return [
'name' => 'required|min:3|max:255',
'description' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,draft,paused',
'budget' => 'nullable|decimal|min_value:0',
'start_date' => 'required|date',
'end_date' => 'nullable|date',
'target_audience' => 'nullable|max:500',
'objectives' => 'nullable|max:500',
'tracking_code' => 'nullable|max:100',
'notes' => 'nullable|max:1000'
];
}
/**
* Regras para upload de arquivo
*/
protected function getFileUploadRules(): array
{
return [
'file' => 'required|file|size:5120', // 5MB max
'allowed_types' => 'nullable|in:image,document,video,audio'
];
}
/**
* Regras para upload de imagem
*/
protected function getImageUploadRules(): array
{
return [
'image' => 'required|image|size:2048', // 2MB max
'max_width' => 'nullable|integer|min_value:1|max_value:5000',
'max_height' => 'nullable|integer|min_value:1|max_value:5000'
];
}
// =============================================================================
// MÉTODOS UTILITÁRIOS ADICIONAIS
// =============================================================================
/**
* Redirecionar com mensagem de sucesso
*/
protected function redirectWithSuccess(string $url, string $message): void
{
$separator = strpos($url, '?') !== false ? '&' : '?';
header("Location: {$url}{$separator}success=" . urlencode($message));
exit();
}
/**
* Redirecionar com mensagem de erro
*/
protected function redirectWithError(string $url, string $message): void
{
$separator = strpos($url, '?') !== false ? '&' : '?';
header("Location: {$url}{$separator}error=" . urlencode($message));
exit();
}
/**
* Verificar se é requisição AJAX
*/
protected function isAjaxRequest(): bool
{
return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}
/**
* Verificar se é requisição POST
*/
protected function isPostRequest(): bool
{
return $_SERVER['REQUEST_METHOD'] === 'POST';
}
/**
* Verificar se é requisição GET
*/
protected function isGetRequest(): bool
{
return $_SERVER['REQUEST_METHOD'] === 'GET';
}
/**
* Obter IP do cliente
*/
protected function getClientIp(): string
{
$ipKeys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
foreach ($ipKeys as $key) {
if (!empty($_SERVER[$key])) {
$ip = $_SERVER[$key];
if (strpos($ip, ',') !== false) {
$ip = trim(explode(',', $ip)[0]);
}
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
/**
* Obter User Agent
*/
protected function getUserAgent(): string
{
return $_SERVER['HTTP_USER_AGENT'] ?? '';
}
/**
* Log de acesso
*/
protected function logAccess(string $action, array $context = []): void
{
$context['ip'] = $this->getClientIp();
$context['user_agent'] = $this->getUserAgent();
$context['user_id'] = Auth::id();
$context['action'] = $action;
ErrorReporter::info("Access: $action", $context);
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Handles hostname-based branding configurations.
*/
class Branding
{
private static ?array $config = null;
private static ?array $currentBranding = null;
/**
* Loads the branding configuration file.
*/
private static function loadConfig(): void
{
if (self::$config === null) {
$configPath = __DIR__ . '/../Config/branding.php';
if (file_exists($configPath)) {
self::$config = require $configPath;
} else {
self::$config = [];
}
}
}
/**
* Get the branding configuration for the current hostname.
*
* It first attempts an exact match on the hostname. If not found, it will
* iterate through configured hostnames to find a partial match (e.g., 'clienteA.com'
* will match a request from 'analytics.clienteA.com').
*
* @return array The configuration array for the matched host, or the default settings.
*/
public static function get(): array
{
if (self::$currentBranding !== null) {
return self::$currentBranding;
}
self::loadConfig();
$hostname = $_SERVER['HTTP_HOST'] ?? 'default';
$defaultConfig = self::$config['default'] ?? [];
// 1. Novo: Matching por string de hostnames separados por vírgula
foreach (self::$config as $configHost => $settings) {
if ($configHost === 'default') continue;
$patterns = explode(',', $configHost);
foreach ($patterns as $pattern) {
if (fnmatch(trim($pattern), $hostname)) {
self::$currentBranding = array_merge($defaultConfig, $settings);
return self::$currentBranding;
}
}
}
// 2. Fallback para default
self::$currentBranding = $defaultConfig;
return self::$currentBranding;
}
/**
* Get the current client ID based on hostname
*/
public static function getClientId(): string
{
$branding = self::get();
return $branding['client_id'] ?? 'default';
}
}
+305
View File
@@ -0,0 +1,305 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Sistema de Cache Simples
*
* Fornece funcionalidades de cache para melhorar a performance da aplicação.
* Suporta cache em ficheiro e preparado para Redis no futuro.
*/
class Cache
{
private string $cachePath;
private int $defaultTtl;
private bool $enabled;
private ?Logger $logger = null;
public function __construct()
{
$this->cachePath = PathManager::getCachePath() . '/';
$this->defaultTtl = 3600; // 1 hora por padrão
$this->enabled = true;
$this->ensureCacheDirectory();
}
private function getLogger(): Logger
{
if ($this->logger === null) {
$this->logger = new Logger('debug'); // Usar nível debug para cache
}
return $this->logger;
}
/**
* Obter valor do cache
*/
public function get(string $key): mixed
{
if (!$this->enabled) {
$this->getLogger()->cache('get', $key, false, ['reason' => 'cache_disabled']);
return null;
}
$filename = $this->getCacheFilename($key);
if (!file_exists($filename)) {
$this->getLogger()->cache('get', $key, false, ['reason' => 'file_not_found']);
return null;
}
$data = file_get_contents($filename);
if ($data === false) {
$this->getLogger()->cache('get', $key, false, ['reason' => 'read_error']);
return null;
}
$cached = json_decode($data, true);
if ($cached === null) {
$this->getLogger()->cache('get', $key, false, ['reason' => 'json_decode_error']);
return null;
}
// Verificar se expirou
if (time() > $cached['expires']) {
$this->delete($key);
$this->getLogger()->cache('get', $key, false, ['reason' => 'expired']);
return null;
}
$this->getLogger()->cache('get', $key, true, ['size' => strlen($data)]);
return $cached['value'];
}
/**
* Guardar valor no cache
*/
public function set(string $key, mixed $value, ?int $ttl = null): bool
{
if (!$this->enabled) {
$this->getLogger()->cache('set', $key, false, ['reason' => 'cache_disabled']);
return false;
}
$ttl = $ttl ?? $this->defaultTtl;
$filename = $this->getCacheFilename($key);
$data = [
'value' => $value,
'expires' => time() + $ttl,
'created' => time()
];
$jsonData = json_encode($data);
$result = file_put_contents($filename, $jsonData);
$success = $result !== false;
$this->getLogger()->cache('set', $key, $success, [
'ttl' => $ttl,
'size' => strlen($jsonData)
]);
return $success;
}
/**
* Eliminar valor do cache
*/
public function delete(string $key): bool
{
$filename = $this->getCacheFilename($key);
if (file_exists($filename)) {
$result = unlink($filename);
$this->getLogger()->cache('delete', $key, $result);
return $result;
}
$this->getLogger()->cache('delete', $key, true, ['reason' => 'file_not_found']);
return true;
}
/**
* Verificar se existe no cache
*/
public function has(string $key): bool
{
return $this->get($key) !== null;
}
/**
* Limpar todo o cache
*/
public function clear(): bool
{
$files = glob($this->cachePath . '*.cache');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
return true;
}
/**
* Limpar cache de analytics
*/
public function clearAnalytics(): bool
{
$files = glob($this->cachePath . '*analytics*');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
return true;
}
/**
* Obter estatísticas do cache
*/
public function getStats(): array
{
$files = glob($this->cachePath . '*.cache');
$totalSize = 0;
$expiredCount = 0;
$validCount = 0;
foreach ($files as $file) {
$size = filesize($file);
$totalSize += $size;
$data = file_get_contents($file);
$cached = json_decode($data, true);
if ($cached && time() > $cached['expires']) {
$expiredCount++;
} else {
$validCount++;
}
}
return [
'total_files' => count($files),
'valid_files' => $validCount,
'expired_files' => $expiredCount,
'total_size' => $this->formatBytes($totalSize),
'cache_path' => $this->cachePath
];
}
/**
* Limpar cache expirado
*/
public function gc(): int
{
$files = glob($this->cachePath . '*.cache');
$deletedCount = 0;
foreach ($files as $file) {
$data = file_get_contents($file);
$cached = json_decode($data, true);
if ($cached && time() > $cached['expires']) {
if (unlink($file)) {
$deletedCount++;
}
}
}
return $deletedCount;
}
/**
* Ativar/desativar cache
*/
public function setEnabled(bool $enabled): void
{
$this->enabled = $enabled;
}
/**
* Cache com callback (memoização)
*/
public function remember(string $key, callable $callback, ?int $ttl = null): mixed
{
$value = $this->get($key);
if ($value !== null) {
$this->getLogger()->cache('remember', $key, true, ['reason' => 'cache_hit']);
return $value;
}
$this->getLogger()->cache('remember', $key, true, ['reason' => 'cache_miss']);
$value = $callback();
$this->set($key, $value, $ttl);
return $value;
}
/**
* Cache para APIs
*/
public function rememberApi(string $endpoint, callable $callback, ?int $ttl = null): array
{
$key = 'api_' . md5($endpoint);
return $this->remember($key, function() use ($callback) {
try {
$result = $callback();
return [
'status' => 'success',
'data' => $result,
'cached_at' => time()
];
} catch (\Exception $e) {
return [
'status' => 'error',
'message' => $e->getMessage(),
'cached_at' => time()
];
}
}, $ttl);
}
/**
* Obter nome do ficheiro de cache
*/
private function getCacheFilename(string $key): string
{
$safeKey = preg_replace('/[^a-zA-Z0-9_-]/', '_', $key);
return $this->cachePath . $safeKey . '.cache';
}
/**
* Garantir que o diretório de cache existe
*/
private function ensureCacheDirectory(): void
{
if (!is_dir($this->cachePath)) {
mkdir($this->cachePath, 0755, true);
}
}
/**
* Formatar bytes para leitura humana
*/
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, 2) . ' ' . $units[$pow];
}
}
+287
View File
@@ -0,0 +1,287 @@
<?php
declare(strict_types=1);
namespace App\Core\Cache;
use Redis;
use Exception;
/**
* Redis Cache Manager
* Gestor de cache Redis para o BitReport CRM
*/
class RedisManager
{
private ?Redis $redis = null;
private string $prefix;
private int $defaultTtl;
private bool $enabled;
public function __construct(
string $host = '127.0.0.1',
int $port = 6379,
string $password = '',
int $database = 0,
string $prefix = 'bitreport:',
int $defaultTtl = 3600
) {
$this->prefix = $prefix;
$this->defaultTtl = $defaultTtl;
$this->enabled = false;
try {
$this->redis = new Redis();
$this->redis->connect($host, $port);
if (!empty($password)) {
$this->redis->auth($password);
}
$this->redis->select($database);
$this->enabled = true;
} catch (Exception $e) {
// Redis não disponível, usar cache em memória
error_log("Redis não disponível: " . $e->getMessage());
}
}
/**
* Verificar se o Redis está disponível
*/
public function isEnabled(): bool
{
return $this->enabled && $this->redis !== null;
}
/**
* Obter valor do cache
*/
public function get(string $key)
{
if (!$this->isEnabled()) {
return null;
}
try {
$value = $this->redis->get($this->prefix . $key);
return $value !== false ? json_decode($value, true) : null;
} catch (Exception $e) {
error_log("Erro ao obter cache Redis: " . $e->getMessage());
return null;
}
}
/**
* Definir valor no cache
*/
public function set(string $key, $value, ?int $ttl = null): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
$ttl = $ttl ?? $this->defaultTtl;
$serializedValue = json_encode($value);
if ($ttl > 0) {
return $this->redis->setex($this->prefix . $key, $ttl, $serializedValue);
} else {
return $this->redis->set($this->prefix . $key, $serializedValue);
}
} catch (Exception $e) {
error_log("Erro ao definir cache Redis: " . $e->getMessage());
return false;
}
}
/**
* Eliminar valor do cache
*/
public function delete(string $key): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
return $this->redis->del($this->prefix . $key) > 0;
} catch (Exception $e) {
error_log("Erro ao eliminar cache Redis: " . $e->getMessage());
return false;
}
}
/**
* Verificar se a chave existe
*/
public function exists(string $key): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
return $this->redis->exists($this->prefix . $key);
} catch (Exception $e) {
error_log("Erro ao verificar cache Redis: " . $e->getMessage());
return false;
}
}
/**
* Incrementar valor
*/
public function increment(string $key, int $value = 1): int
{
if (!$this->isEnabled()) {
return 0;
}
try {
return $this->redis->incrBy($this->prefix . $key, $value);
} catch (Exception $e) {
error_log("Erro ao incrementar cache Redis: " . $e->getMessage());
return 0;
}
}
/**
* Decrementar valor
*/
public function decrement(string $key, int $value = 1): int
{
if (!$this->isEnabled()) {
return 0;
}
try {
return $this->redis->decrBy($this->prefix . $key, $value);
} catch (Exception $e) {
error_log("Erro ao decrementar cache Redis: " . $e->getMessage());
return 0;
}
}
/**
* Definir tempo de expiração
*/
public function expire(string $key, int $ttl): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
return $this->redis->expire($this->prefix . $key, $ttl);
} catch (Exception $e) {
error_log("Erro ao definir expiração Redis: " . $e->getMessage());
return false;
}
}
/**
* Obter tempo restante de expiração
*/
public function ttl(string $key): int
{
if (!$this->isEnabled()) {
return -1;
}
try {
return $this->redis->ttl($this->prefix . $key);
} catch (Exception $e) {
error_log("Erro ao obter TTL Redis: " . $e->getMessage());
return -1;
}
}
/**
* Eliminar todas as chaves com prefixo
*/
public function clear(string $pattern = '*'): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
$keys = $this->redis->keys($this->prefix . $pattern);
if (!empty($keys)) {
return $this->redis->del($keys) > 0;
}
return true;
} catch (Exception $e) {
error_log("Erro ao limpar cache Redis: " . $e->getMessage());
return false;
}
}
/**
* Obter estatísticas do Redis
*/
public function getStats(): array
{
if (!$this->isEnabled()) {
return [
'enabled' => false,
'connected' => false,
'keys' => 0,
'memory' => 0
];
}
try {
$info = $this->redis->info();
$keys = $this->redis->dbSize();
return [
'enabled' => true,
'connected' => true,
'keys' => $keys,
'memory' => $info['used_memory_human'] ?? '0B',
'version' => $info['redis_version'] ?? 'unknown',
'uptime' => $info['uptime_in_seconds'] ?? 0
];
} catch (Exception $e) {
return [
'enabled' => true,
'connected' => false,
'error' => $e->getMessage()
];
}
}
/**
* Obter instância Redis (para operações avançadas)
*/
public function getRedis(): ?Redis
{
return $this->redis;
}
/**
* Fechar conexão
*/
public function close(): void
{
if ($this->redis !== null) {
try {
$this->redis->close();
} catch (Exception $e) {
error_log("Erro ao fechar conexão Redis: " . $e->getMessage());
}
$this->redis = null;
$this->enabled = false;
}
}
/**
* Destructor
*/
public function __destruct()
{
$this->close();
}
}
+197
View File
@@ -0,0 +1,197 @@
<?php
declare(strict_types=1);
namespace App\Core\Config;
/**
* Gestão centralizada de configurações de APIs externas
*/
class ApiConfig
{
private static ?self $instance = null;
private array $config = [];
private function __construct()
{
$this->loadConfig();
}
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Carregar configurações do ambiente
*/
private function loadConfig(): void
{
$this->config = [
'coinmarketcap' => [
'api_key' => $_ENV['COINMARKETCAP_API_KEY'] ?? null,
'base_url' => 'https://pro-api.coinmarketcap.com/v1',
'timeout' => 10,
'monthly_limit' => 10000,
'daily_limit' => 333, // Deixar margem de segurança
],
'google_maps' => [
'api_key' => $_ENV['GOOGLE_MAPS_API_KEY'] ?? null,
'base_url' => 'https://maps.googleapis.com/maps/api',
],
'stripe' => [
'api_key' => $_ENV['STRIPE_API_KEY'] ?? null,
'publishable_key' => $_ENV['STRIPE_PUBLISHABLE_KEY'] ?? null,
'webhook_secret' => $_ENV['STRIPE_WEBHOOK_SECRET'] ?? null,
],
'paypal' => [
'client_id' => $_ENV['PAYPAL_CLIENT_ID'] ?? null,
'client_secret' => $_ENV['PAYPAL_CLIENT_SECRET'] ?? null,
'mode' => $_ENV['PAYPAL_MODE'] ?? 'sandbox', // sandbox ou live
]
];
}
/**
* Obter configuração de uma API específica
*/
public function get(string $api, ?string $key = null)
{
if (!isset($this->config[$api])) {
throw new \InvalidArgumentException("API configuration not found: {$api}");
}
if ($key === null) {
return $this->config[$api];
}
if (!isset($this->config[$api][$key])) {
throw new \InvalidArgumentException("API configuration key not found: {$api}.{$key}");
}
return $this->config[$api][$key];
}
/**
* Verificar se uma API está configurada
*/
public function isConfigured(string $api): bool
{
return isset($this->config[$api]) && !empty($this->config[$api]['api_key']);
}
/**
* Obter todas as APIs disponíveis
*/
public function getAvailableApis(): array
{
return array_keys($this->config);
}
/**
* Obter status de configuração de todas as APIs
*/
public function getConfigurationStatus(): array
{
$status = [];
foreach ($this->config as $api => $config) {
$status[$api] = [
'configured' => $this->isConfigured($api),
'has_api_key' => !empty($config['api_key']),
'config_keys' => array_keys($config)
];
}
return $status;
}
/**
* Validar configuração de uma API
*/
public function validateApiConfig(string $api): array
{
$errors = [];
if (!isset($this->config[$api])) {
$errors[] = "API '{$api}' not found in configuration";
return $errors;
}
$config = $this->config[$api];
switch ($api) {
case 'coinmarketcap':
if (empty($config['api_key'])) {
$errors[] = "CoinMarketCap API key is required. Set COINMARKETCAP_API_KEY in config.env";
}
if (strlen($config['api_key'] ?? '') < 30) {
$errors[] = "CoinMarketCap API key appears to be invalid (too short)";
}
break;
case 'google_maps':
if (empty($config['api_key'])) {
$errors[] = "Google Maps API key is required. Set GOOGLE_MAPS_API_KEY in config.env";
}
break;
case 'stripe':
if (empty($config['api_key'])) {
$errors[] = "Stripe API key is required. Set STRIPE_API_KEY in config.env";
}
if (empty($config['publishable_key'])) {
$errors[] = "Stripe publishable key is required. Set STRIPE_PUBLISHABLE_KEY in config.env";
}
break;
case 'paypal':
if (empty($config['client_id'])) {
$errors[] = "PayPal client ID is required. Set PAYPAL_CLIENT_ID in config.env";
}
if (empty($config['client_secret'])) {
$errors[] = "PayPal client secret is required. Set PAYPAL_CLIENT_SECRET in config.env";
}
if (!in_array($config['mode'], ['sandbox', 'live'])) {
$errors[] = "PayPal mode must be 'sandbox' or 'live'";
}
break;
}
return $errors;
}
/**
* Obter headers padrão para uma API
*/
public function getHeaders(string $api): array
{
switch ($api) {
case 'coinmarketcap':
return [
'X-CMC_PRO_API_KEY: ' . $this->get('coinmarketcap', 'api_key'),
'Accept: application/json'
];
case 'stripe':
return [
'Authorization: Bearer ' . $this->get('stripe', 'api_key'),
'Content-Type: application/x-www-form-urlencoded'
];
default:
return [];
}
}
/**
* Construir URL completa para uma API
*/
public function buildUrl(string $api, string $endpoint): string
{
$baseUrl = $this->get($api, 'base_url');
return rtrim($baseUrl, '/') . '/' . ltrim($endpoint, '/');
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Core\Config;
// Caminhos absolutos globais
if (!defined('ROOT_PATH')) define('ROOT_PATH', dirname(__DIR__, 3));
if (!defined('APP_PATH')) define('APP_PATH', ROOT_PATH . '/app');
if (!defined('VIEW_PATH')) define('VIEW_PATH', APP_PATH . '/Views');
if (!defined('PUBLIC_PATH')) define('PUBLIC_PATH', ROOT_PATH . '/public');
if (!defined('STORAGE_PATH')) define('STORAGE_PATH', ROOT_PATH . '/storage');
if (!defined('CACHE_PATH')) define('CACHE_PATH', STORAGE_PATH . '/cache');
if (!defined('LOG_PATH')) define('LOG_PATH', ROOT_PATH . '/logs');
if (!defined('MODULES_PATH')) define('MODULES_PATH', APP_PATH . '/Modules');
if (!defined('CONFIG_PATH')) define('CONFIG_PATH', APP_PATH . '/Config');
// URLs
if (!defined('BASE_URL')) {
define('BASE_URL', $_ENV['APP_URL'] ?? 'http://localhost:8888');
define('ASSETS_URL', BASE_URL . '/assets');
define('STORAGE_URL', BASE_URL . '/storage');
}
// Other constants
if (!defined('DEFAULT_LANG')) define('DEFAULT_LANG', 'pt');
if (!defined('DEFAULT_TIMEZONE')) define('DEFAULT_TIMEZONE', 'Europe/Lisbon');
if (!defined('DEFAULT_CHARSET')) define('DEFAULT_CHARSET', 'UTF-8');
// Default Client Configuration
if (!defined('DEFAULT_CLIENT_NAME')) define('DEFAULT_CLIENT_NAME', 'Performix Media');
if (!defined('DEFAULT_CLIENT_LOGO')) define('DEFAULT_CLIENT_LOGO', ASSETS_URL . '/images/brands/performixmedia-logo.png');
if (!defined('DEFAULT_CLIENT_LOCATION')) define('DEFAULT_CLIENT_LOCATION', 'Portugal');
if (!defined('DEFAULT_CLIENT_DEALS')) define('DEFAULT_CLIENT_DEALS', '15');
if (!defined('DEFAULT_CLIENT_REVENUE')) define('DEFAULT_CLIENT_REVENUE', '1.2M');
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Core;
class CrontabReader
{
/**
* Lê o crontab do sistema e devolve um array de CrontabTask.
*/
public static function read(): array
{
$output = [];
exec('crontab -l 2>/dev/null', $output);
$tasks = [];
$pendingComments = [];
foreach ($output as $line) {
$trim = trim($line);
if ($trim === '') continue;
if (strpos($trim, '#') === 0) {
$pendingComments[] = ltrim($trim, '# ');
continue;
}
// Ignora env vars (ex: MAILTO=)
if (preg_match('/^[A-Z0-9_]+=/', $trim)) continue;
$task = new CrontabTask($trim, $pendingComments);
$tasks[] = $task;
$pendingComments = [];
}
return $tasks;
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace App\Core;
class CrontabTask
{
public string $id;
public string $schedule;
public string $command;
public ?string $args = null;
public ?string $redirect = null;
public ?string $raw = null;
public array $comments = [];
public ?string $special = null; // @reboot, @hourly, etc.
public function __construct(string $rawLine, array $comments = [])
{
$this->raw = $rawLine;
$this->comments = $comments;
$this->parse($rawLine);
$this->id = md5(trim($rawLine));
}
private function parse(string $line): void
{
// Remove inline comments (mas guarda para display)
$line = preg_replace('/\s+#.*/', '', $line);
// Suporte a @reboot, @hourly, etc.
if (preg_match('/^(@\w+)\s+(.*)$/', $line, $matches)) {
$this->special = $matches[1];
$this->schedule = $matches[1];
$rest = $matches[2];
} else {
// Split schedule (5 campos) + comando
$parts = preg_split('/\s+/', $line, 6);
if (count($parts) < 6) {
$this->schedule = '';
$this->command = '';
return;
}
[$min, $hour, $dom, $mon, $dow, $rest] = $parts;
$this->schedule = "$min $hour $dom $mon $dow";
}
// Separa comando, args e redirecionamentos
if (preg_match('/^([^\s]+)(.*?)(\s+>\s*.+)?$/', $rest, $matches)) {
$this->command = trim($matches[1]);
$this->args = isset($matches[2]) ? trim($matches[2]) : null;
$this->redirect = isset($matches[3]) ? trim($matches[3]) : null;
} else {
$this->command = trim($rest);
}
}
public function toArray(): array
{
return [
'id' => $this->id,
'schedule' => $this->schedule,
'command' => $this->command,
'args' => $this->args,
'redirect' => $this->redirect,
'raw' => $this->raw,
'comments' => $this->comments,
'special' => $this->special,
];
}
}
+295
View File
@@ -0,0 +1,295 @@
<?php
declare(strict_types=1);
namespace App\Core;
use App\Core\DatabaseManager;
use App\Core\Logger;
use App\Core\ErrorReporter;
/**
* Dashboard Widget Manager
*
* Manages modular dashboard widgets system allowing modules to register
* widgets and users to customize their dashboard layout and content.
*/
class DashboardWidgetManager
{
private ?DatabaseManager $db = null;
private ?Logger $logger = null;
private static ?self $instance = null;
public function __construct()
{
// Lazy loading - não inicializar aqui
}
private function getDb(): DatabaseManager
{
if ($this->db === null) {
$this->db = DatabaseManager::getInstance();
}
return $this->db;
}
private function getLogger(): Logger
{
if ($this->logger === null) {
$this->logger = new Logger();
}
return $this->logger;
}
/**
* Get singleton instance
*/
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Register a widget from a module
*
* @param string $widgetId Unique widget identifier
* @param string $moduleName Module that provides this widget
* @param string $widgetName Display name
* @param string $widgetClass PHP class that renders the widget
* @param array $config Widget configuration
* @return bool Success status
*/
public function registerWidget(
string $widgetId,
string $moduleName,
string $widgetName,
string $widgetClass,
array $config = []
): bool {
try {
$defaultConfig = [
'description' => $config['description'] ?? '',
'method' => $config['method'] ?? 'render',
'size' => $config['size'] ?? 'medium',
'category' => $config['category'] ?? 'general',
'default_config' => $config['default_config'] ?? null
];
$this->getDb()->query("
INSERT INTO dashboard_widgets (
widget_id, module_name, widget_name, widget_description,
widget_class, widget_method, default_config, widget_size,
widget_category, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
ON DUPLICATE KEY UPDATE
widget_name = VALUES(widget_name),
widget_description = VALUES(widget_description),
widget_class = VALUES(widget_class),
widget_method = VALUES(widget_method),
default_config = VALUES(default_config),
widget_size = VALUES(widget_size),
widget_category = VALUES(widget_category),
updated_at = CURRENT_TIMESTAMP
", [
$widgetId,
$moduleName,
$widgetName,
$defaultConfig['description'],
$widgetClass,
$defaultConfig['method'],
$defaultConfig['default_config'] ? json_encode($defaultConfig['default_config']) : null,
$defaultConfig['size'],
$defaultConfig['category']
]);
$this->getLogger()->info("Widget registered: {$widgetId} from module {$moduleName}");
return true;
} catch (\Exception $e) {
ErrorReporter::report($e);
$this->getLogger()->error("Failed to register widget {$widgetId}: " . $e->getMessage());
return false;
}
}
/**
* Get available widgets for a user
*
* @param int $userId User ID
* @return array Available widgets
*/
public function getAvailableWidgets(int $userId): array
{
try {
return $this->getDb()->fetchAll("
SELECT
dw.*,
udw.is_visible,
udw.position_order,
udw.widget_config as user_config,
udw.widget_size as user_size
FROM dashboard_widgets dw
LEFT JOIN user_dashboard_widgets udw ON dw.widget_id = udw.widget_id AND udw.user_id = ?
WHERE dw.is_active = 1
ORDER BY dw.widget_category, dw.widget_name
", [$userId]);
} catch (\Exception $e) {
ErrorReporter::report($e);
return [];
}
}
/**
* Get user's dashboard widgets in display order
*
* @param int $userId User ID
* @return array User's active widgets
*/
public function getUserDashboardWidgets(int $userId): array
{
try {
return $this->getDb()->fetchAll("
SELECT
dw.*,
udw.position_order,
udw.widget_config as user_config,
COALESCE(udw.widget_size, dw.widget_size) as effective_size
FROM dashboard_widgets dw
INNER JOIN user_dashboard_widgets udw ON dw.widget_id = udw.widget_id
WHERE udw.user_id = ? AND udw.is_visible = 1 AND dw.is_active = 1
ORDER BY udw.position_order ASC, dw.widget_name ASC
", [$userId]);
} catch (\Exception $e) {
ErrorReporter::report($e);
return [];
}
}
/**
* Update user widget configuration
*
* @param int $userId User ID
* @param string $widgetId Widget ID
* @param array $config Widget configuration
* @return bool Success status
*/
public function updateUserWidget(int $userId, string $widgetId, array $config): bool
{
try {
$this->getDb()->query("
INSERT INTO user_dashboard_widgets (
user_id, widget_id, position_order, widget_size,
widget_config, is_visible
) VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
position_order = VALUES(position_order),
widget_size = VALUES(widget_size),
widget_config = VALUES(widget_config),
is_visible = VALUES(is_visible),
updated_at = CURRENT_TIMESTAMP
", [
$userId,
$widgetId,
$config['position_order'] ?? 0,
$config['widget_size'] ?? null,
isset($config['widget_config']) ? json_encode($config['widget_config']) : null,
$config['is_visible'] ?? 1
]);
return true;
} catch (\Exception $e) {
ErrorReporter::report($e);
return false;
}
}
/**
* Render a widget
*
* @param array $widget Widget configuration
* @return string Rendered widget HTML
*/
public function renderWidget(array $widget): string
{
try {
$className = $widget['widget_class'];
$method = $widget['widget_method'] ?? 'render';
if (!class_exists($className)) {
throw new \Exception("Widget class not found: {$className}");
}
$config = [];
if (!empty($widget['user_config'])) {
$config = json_decode($widget['user_config'], true) ?? [];
} elseif (!empty($widget['default_config'])) {
$config = json_decode($widget['default_config'], true) ?? [];
}
// Call the widget render method
if (method_exists($className, $method)) {
return call_user_func([$className, $method], $config);
} else {
return $this->renderErrorWidget("Method {$method} not found in {$className}");
}
} catch (\Exception $e) {
ErrorReporter::report($e);
return $this->renderErrorWidget("Failed to render widget: " . $e->getMessage());
}
}
/**
* Render error widget
*
* @param string $message Error message
* @return string Error widget HTML
*/
private function renderErrorWidget(string $message): string
{
return '<div class="alert alert-danger">
<i class="ri-error-warning-line"></i> Widget Error: ' . htmlspecialchars($message) . '
</div>';
}
/**
* Initialize default widgets for new user
*
* @param int $userId User ID
* @return bool Success status
*/
public function initializeDefaultWidgets(int $userId): bool
{
try {
// Get some default widgets to enable for new users
$defaultWidgets = $this->getDb()->fetchAll("
SELECT widget_id
FROM dashboard_widgets
WHERE is_active = 1
AND widget_category IN ('analytics', 'crm', 'general')
ORDER BY widget_name
LIMIT 6
");
$position = 0;
foreach ($defaultWidgets as $widget) {
$this->updateUserWidget($userId, $widget['widget_id'], [
'position_order' => $position++,
'is_visible' => 1
]);
}
return true;
} catch (\Exception $e) {
ErrorReporter::report($e);
return false;
}
}
}
File diff suppressed because it is too large. Load diff
+472
View File
@@ -0,0 +1,472 @@
<?php
declare(strict_types=1);
namespace App\Core\Database;
use App\Core\DatabaseManager;
use App\Core\ErrorReporter;
use App\Core\Logger;
use App\Core\PathManager;
class MigrationManager
{
private DatabaseManager $db;
private SchemaBuilder $schema;
private Logger $logger;
private string $migrationsPath;
public function __construct()
{
$this->db = DatabaseManager::getInstance();
$this->schema = new SchemaBuilder();
$this->logger = new Logger();
// No longer needed - all migrations are now in modules
$this->migrationsPath = '';
}
/**
* Run all pending migrations with intelligent system
*/
public function migrate(): array
{
$results = [
'applied' => [],
'skipped' => [],
'errors' => [],
'warnings' => []
];
try {
$this->logger->info("🚀 Starting intelligent migration system");
// Ensure migrations table exists
$this->ensureMigrationsTable();
// Get all migration files from both old and new locations
$migrationFiles = $this->getAllMigrationFiles();
$processedMigrations = [];
$this->logger->info("📋 Found " . count($migrationFiles) . " migration files");
foreach ($migrationFiles as $file) {
$migration = $this->loadMigration($file);
if (!$migration) {
$error = "Failed to load migration: $file";
$results['errors'][] = $error;
$this->logger->error("❌ $error");
continue;
}
$migrationName = $migration->getName();
// Skip if we already processed this migration
if (in_array($migrationName, $processedMigrations)) {
$this->logger->info("⏭️ Skipping duplicate migration: $migrationName");
continue;
}
$processedMigrations[] = $migrationName;
if ($migration->isApplied()) {
$results['skipped'][] = $migrationName;
$this->logger->info("✅ Migration already applied: $migrationName");
continue;
}
$this->logger->info("🔄 Running migration: $migrationName");
// Run the migration with intelligent system
if ($migration->run()) {
$migration->markAsApplied();
$results['applied'][] = $migrationName;
$this->logger->info("✅ Migration applied successfully: $migrationName");
} else {
$error = "Migration failed: $migrationName";
$results['errors'][] = $error;
$this->logger->error("❌ $error");
}
}
$this->logger->info("🎉 Migration system completed");
$this->logger->info("📊 Results: " . count($results['applied']) . " applied, " .
count($results['skipped']) . " skipped, " .
count($results['errors']) . " errors");
} catch (\Exception $e) {
$error = "Migration system error: " . $e->getMessage();
$results['errors'][] = $error;
$this->logger->error("❌ $error");
ErrorReporter::report($e, ['context' => 'migration_manager_migrate']);
}
return $results;
}
/**
* Rollback last batch of migrations with safety checks
*/
public function rollback(int $steps = 1): array
{
$results = [
'rolled_back' => [],
'errors' => [],
'warnings' => []
];
try {
$this->logger->info("🔄 Starting rollback of $steps migration(s)");
$migrations = $this->getLastBatchMigrations($steps);
if (empty($migrations)) {
$this->logger->info("ℹ️ No migrations to rollback");
return $results;
}
foreach ($migrations as $migrationName) {
$migration = $this->loadMigrationByName($migrationName);
if (!$migration) {
$error = "Failed to load migration for rollback: $migrationName";
$results['errors'][] = $error;
$this->logger->error("❌ $error");
continue;
}
$this->logger->info("🔄 Rolling back migration: $migrationName");
if ($migration->rollback()) {
$migration->markAsRolledBack();
$results['rolled_back'][] = $migrationName;
$this->logger->info("✅ Migration rolled back successfully: $migrationName");
} else {
$error = "Rollback failed: $migrationName";
$results['errors'][] = $error;
$this->logger->error("❌ $error");
}
}
$this->logger->info("🎉 Rollback completed");
$this->logger->info("📊 Results: " . count($results['rolled_back']) . " rolled back, " .
count($results['errors']) . " errors");
} catch (\Exception $e) {
$error = "Rollback system error: " . $e->getMessage();
$results['errors'][] = $error;
$this->logger->error("❌ $error");
ErrorReporter::report($e, ['context' => 'migration_manager_rollback']);
}
return $results;
}
/**
* Show migration status with detailed information
*/
public function status(): array
{
$status = [];
try {
$this->logger->info("📊 Checking migration status");
$migrationFiles = $this->getAllMigrationFiles();
$appliedMigrations = $this->getAppliedMigrations();
$processedMigrations = [];
$this->logger->info("📋 Found " . count($migrationFiles) . " migration files");
$this->logger->info("✅ Found " . count($appliedMigrations) . " applied migrations");
foreach ($migrationFiles as $file) {
$migration = $this->loadMigration($file);
if (!$migration) continue;
$migrationName = $migration->getName();
// Skip if we already processed this migration
if (in_array($migrationName, $processedMigrations)) {
continue;
}
$processedMigrations[] = $migrationName;
$isApplied = in_array($migrationName, $appliedMigrations);
$status[] = [
'name' => $migrationName,
'file' => basename($file),
'applied' => $isApplied,
'applied_at' => $isApplied ? $this->getMigrationAppliedAt($migrationName) : null,
'status' => $isApplied ? '✅ Applied' : '⏳ Pending'
];
}
$this->logger->info("📊 Status check completed");
} catch (\Exception $e) {
$this->logger->error("❌ Status check error: " . $e->getMessage());
ErrorReporter::report($e, ['context' => 'migration_manager_status']);
}
return $status;
}
/**
* Get all migration files from module directories
*/
private function getAllMigrationFiles(): array
{
return PathManager::getAllMigrationFiles();
}
/**
* Load migration from file with error handling
*/
private function loadMigration(string $file): ?Migration
{
try {
// Get the file content to extract the class name
$content = file_get_contents($file);
// Extract class name using regex
if (preg_match('/class\s+(\w+)\s+extends\s+Migration/', $content, $matches)) {
$className = $matches[1];
// Get the namespace from the file
$namespace = '';
if (preg_match('/namespace\s+([^;]+);/', $content, $namespaceMatches)) {
$namespace = $namespaceMatches[1] . '\\';
}
$fullClassName = $namespace . $className;
// Load the file
require_once $file;
// Check if the class exists and is a subclass of Migration
if (class_exists($fullClassName) && is_subclass_of($fullClassName, 'App\Core\Database\Migration')) {
return new $fullClassName();
}
}
$this->logger->warning("⚠️ Could not load migration from file: $file");
return null;
} catch (\Exception $e) {
$this->logger->error("❌ Error loading migration from file $file: " . $e->getMessage());
ErrorReporter::report($e, ['context' => 'migration_manager_load', 'file' => $file]);
return null;
}
}
/**
* Load migration by class name
*/
private function loadMigrationByName(string $migrationName): ?Migration
{
$files = $this->getAllMigrationFiles();
foreach ($files as $file) {
$migration = $this->loadMigration($file);
if ($migration && $migration->getName() === $migrationName) {
return $migration;
}
}
$this->logger->warning("⚠️ Could not find migration: $migrationName");
return null;
}
/**
* Get applied migrations
*/
private function getAppliedMigrations(): array
{
try {
$result = $this->db->fetchAll("SELECT migration FROM migrations ORDER BY executed_at ASC");
return array_column($result, 'migration');
} catch (\Exception $e) {
$this->logger->warning("⚠️ Could not get applied migrations: " . $e->getMessage());
return [];
}
}
/**
* Get last batch migrations
*/
private function getLastBatchMigrations(int $steps = 1): array
{
try {
$result = $this->db->fetchAll(
"SELECT migration FROM migrations ORDER BY batch DESC, executed_at DESC LIMIT ?",
[$steps]
);
return array_column($result, 'migration');
} catch (\Exception $e) {
$this->logger->warning("⚠️ Could not get last batch migrations: " . $e->getMessage());
return [];
}
}
/**
* Get migration applied timestamp
*/
private function getMigrationAppliedAt(string $migrationName): ?string
{
try {
$result = $this->db->fetch(
"SELECT executed_at FROM migrations WHERE migration = ?",
[$migrationName]
);
return $result['executed_at'] ?? null;
} catch (\Exception $e) {
$this->logger->warning("⚠️ Could not get migration timestamp for $migrationName: " . $e->getMessage());
return null;
}
}
/**
* Ensure migrations table exists with intelligent system
*/
private function ensureMigrationsTable(): void
{
if (!$this->schema->tableExists('migrations')) {
$this->logger->info("📋 Creating migrations table");
$this->schema->table('migrations')
->bigInteger('id')->autoIncrement()->notNull()
->string('migration', 255)->notNull()
->integer('batch')->notNull()
->timestamp('executed_at')->notNull()
->primaryKey('id')
->index('migration')
->index('batch')
->apply();
$this->logger->info("✅ Migrations table created successfully");
} else {
$this->logger->info("✅ Migrations table already exists");
}
}
/**
* Get database schema diff using intelligent system
*/
public function getSchemaDiff(string $tableName, array $desiredColumns, array $desiredIndexes = []): array
{
$this->logger->info("🔍 Getting schema diff for table: $tableName");
return $this->schema->compareStructures($tableName, $desiredColumns, $desiredIndexes);
}
/**
* Apply schema changes using intelligent system
*/
public function applySchemaChanges(string $tableName, array $changes): bool
{
$this->logger->info("🚀 Applying schema changes to table: $tableName");
return $this->schema->applyChanges($tableName, $changes);
}
/**
* Get current table structure
*/
public function getTableStructure(string $tableName): array
{
return $this->schema->getCurrentStructure($tableName);
}
/**
* Get current table indexes
*/
public function getTableIndexes(string $tableName): array
{
return $this->schema->getCurrentIndexes($tableName);
}
/**
* Check if table exists
*/
public function tableExists(string $tableName): bool
{
return $this->schema->tableExists($tableName);
}
/**
* Get all tables
*/
public function getTables(): array
{
return $this->schema->getTables();
}
/**
* Validate database integrity
*/
public function validateDatabaseIntegrity(): array
{
$results = [
'valid' => true,
'issues' => [],
'warnings' => []
];
try {
$this->logger->info("🔍 Validating database integrity");
$tables = $this->getTables();
foreach ($tables as $tableName) {
// Check if table has primary key
$hasPrimaryKey = $this->db->fetch("
SELECT COUNT(*) as count
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND CONSTRAINT_NAME = 'PRIMARY'
", [$tableName]);
if (($hasPrimaryKey['count'] ?? 0) === 0) {
$warning = "Table $tableName has no PRIMARY KEY";
$results['warnings'][] = $warning;
$this->logger->warning("⚠️ $warning");
}
// Check for orphaned indexes
$indexes = $this->getTableIndexes($tableName);
foreach ($indexes as $indexName => $index) {
if ($indexName !== 'PRIMARY') {
// Check if all columns in index still exist
foreach ($index['columns'] as $column) {
$columnExists = $this->db->fetch("
SELECT COUNT(*) as count
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?
", [$tableName, $column['name']]);
if (($columnExists['count'] ?? 0) === 0) {
$issue = "Index $indexName in table $tableName references non-existent column {$column['name']}";
$results['issues'][] = $issue;
$this->logger->error("❌ $issue");
$results['valid'] = false;
}
}
}
}
}
$this->logger->info("✅ Database integrity validation completed");
$this->logger->info("📊 Results: " . count($results['issues']) . " issues, " .
count($results['warnings']) . " warnings");
} catch (\Exception $e) {
$error = "Database integrity validation error: " . $e->getMessage();
$results['issues'][] = $error;
$results['valid'] = false;
$this->logger->error("❌ $error");
ErrorReporter::report($e, ['context' => 'migration_manager_validate_integrity']);
}
return $results;
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
use App\Core\Database\Migration;
/**
* Add last_login column to users table
*
* Migration to add the missing last_login column that is required
* by the dashboard and user analytics systems.
*/
class AddLastLoginToUsersTable extends Migration
{
/**
* Run the migration
*/
public function up(): void
{
// Add last_login column to users table
$this->addColumn('users', 'last_login', 'TIMESTAMP NULL DEFAULT NULL COMMENT "Last login timestamp for user activity tracking"');
// Add index for better query performance
$this->addIndex('users', 'idx_users_last_login', ['last_login']);
echo "Added last_login column to users table with index\n";
}
/**
* Reverse the migration
*/
public function down(): void
{
// Remove index first
$this->dropIndex('users', 'idx_users_last_login');
// Remove column
$this->dropColumn('users', 'last_login');
echo "Removed last_login column and index from users table\n";
}
/**
* Get migration description
*/
public function getDescription(): string
{
return 'Add last_login column to users table for activity tracking';
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
class AddStatusColumnToCampaignsTable extends Migration
{
/**
* The name of the database connection to use.
* Uses default CRM database (null = default connection)
*/
protected ?string $connection = null;
public function up(): void
{
// Add status column to campaigns table using SchemaBuilder
$this->addColumn('campaigns', 'status', function($table) {
$table->status('status')->default(1)->notNull();
});
// Copy is_active values to status column
$this->db->query("
UPDATE campaigns
SET status = CASE
WHEN is_active = 1 THEN 1
ELSE 0
END
");
// Add index for status using SchemaBuilder
$this->addIndex('campaigns', 'idx_status', ['status']);
}
public function down(): void
{
$this->dropIndex('campaigns', 'idx_status');
$this->dropColumn('campaigns', 'status');
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
class AddStatusColumnToUsersTable extends Migration
{
/**
* The name of the database connection to use.
* Uses default CRM database (null = default connection)
*/
protected ?string $connection = null;
public function up(): void
{
// Add status column to users table using SchemaBuilder
$this->addColumn('users', 'status', function($table) {
$table->status('status')->default(1)->notNull();
});
// Copy is_active values to status column
$this->db->query("
UPDATE users
SET status = CASE
WHEN deleted_at IS NOT NULL THEN -1
WHEN is_active = 1 THEN 1
ELSE 0
END
");
// Add index for status using SchemaBuilder
$this->addIndex('users', 'idx_status', ['status']);
}
public function down(): void
{
$this->dropIndex('users', 'idx_status');
$this->dropColumn('users', 'status');
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
use App\Core\Database\SchemaBuilder;
class ExpandSiteGroupsStatusToVarchar extends Migration
{
public function up(): void
{
$this->log("🔄 Converting site groups status from ENUM to VARCHAR for Google Sheets integration");
// Convert status from ENUM to VARCHAR(50) to support all Google Sheets status values
// Following project preference for VARCHAR over ENUM as documented in DATABASE_SOFT_DELETE_GUIDE.md
$sql = "ALTER TABLE advertising_site_groups
MODIFY COLUMN status VARCHAR(50) NOT NULL DEFAULT 'active'";
$this->db->query($sql);
$this->log("✅ Site groups status converted to VARCHAR(50) successfully");
$this->log("📝 Now supports all Google Sheets status values without ENUM limitations");
}
public function down(): void
{
$this->log("🔄 Reverting site groups status to original ENUM values");
// First, update any non-standard status values to 'inactive'
$this->db->query("UPDATE advertising_site_groups
SET status = 'inactive'
WHERE status NOT IN ('active', 'inactive', 'pending')");
// Revert to original enum (though project prefers VARCHAR)
$sql = "ALTER TABLE advertising_site_groups
MODIFY COLUMN status ENUM('active','inactive','pending')
NOT NULL DEFAULT 'active'";
$this->db->query($sql);
$this->log("✅ Site groups status reverted to original ENUM (not recommended)");
}
public function getDescription(): string
{
return "Convert site groups status from ENUM to VARCHAR(50) for Google Sheets integration";
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
class CreateAnalyticsDailyTable extends Migration
{
/**
* The name of the database connection to use.
* Uses default CRM database for analytics data
*/
protected ?string $connection = null; // CRM database (default)
public function up(): void
{
$this->createTable('analytics_daily', function($table) {
$table->bigInteger('id')->autoIncrement()->notNull()
->integer('page_views')->default(0)->notNull()->comment('Daily page views')
->integer('unique_visitors')->default(0)->notNull()->comment('Daily unique visitors')
->decimal('bounce_rate', 5, 2)->default(0.00)->notNull()->comment('Daily bounce rate percentage')
->decimal('avg_session_duration', 8, 2)->default(0.00)->notNull()->comment('Average session duration in minutes')
->date('date')->notNull()->comment('Date for this analytics record')
->tinyInteger('status')->default(1)->notNull()->comment('0=inactive, 1=active, -1=deleted')
->timestamp('created_at')->default('CURRENT_TIMESTAMP')->notNull()
->timestamp('updated_at')->default('CURRENT_TIMESTAMP')->notNull()
->primaryKey('id')
->index('date')
->index('status')
->unique('date'); // One record per date
});
}
public function down(): void
{
$this->dropTable('analytics_daily');
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
use App\Core\Database\SchemaBuilder;
/**
* Migration: Create Campaign Domains Table
*
* Creates advertising_campaign_domains table for optional campaign-specific domains.
* This allows campaigns to target specific domains within their site group.
*/
class CreateCampaignDomainsTable extends Migration
{
public function up(): void
{
$this->schema->createTable('advertising_campaign_domains', function (SchemaBuilder $table) {
$table->id();
$table->varchar('cuid', 64)->unique()->comment('CUID2 identifier');
$table->unsignedBigInteger('campaign_id')->index()->comment('Foreign key to advertising_campaigns');
$table->unsignedBigInteger('site_domain_id')->index()->comment('Foreign key to advertising_site_domains');
$table->tinyInteger('status')->default(1)->index()->comment('1=active, 0=inactive, -1=deleted');
$table->json('targeting_settings')->nullable()->comment('Domain-specific targeting settings');
$table->unsignedBigInteger('created_by')->index()->comment('User who created this association');
$table->timestamps();
$table->timestamp('deleted_at')->nullable()->index();
// Foreign key constraints
$table->foreignKey('campaign_id', 'advertising_campaigns', 'id', 'CASCADE', 'CASCADE');
$table->foreignKey('site_domain_id', 'advertising_site_domains', 'id', 'CASCADE', 'CASCADE');
$table->foreignKey('created_by', 'users', 'id', 'CASCADE', 'CASCADE');
// Unique constraint to prevent duplicate campaign-domain associations
$table->unique(['campaign_id', 'site_domain_id'], 'unique_campaign_domain');
// Indexes for performance
$table->index(['campaign_id', 'status'], 'idx_campaign_status');
$table->index(['site_domain_id', 'status'], 'idx_domain_status');
});
}
public function down(): void
{
$this->schema->dropTable('advertising_campaign_domains');
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
class CreateCryptoPortfolioTable extends Migration
{
public function up(): void
{
$this->createTable('crypto_portfolio', function($table) {
$table->bigInteger('id')->autoIncrement()->notNull();
$table->bigInteger('user_id')->notNull()->comment('User ID reference');
$table->string('crypto_symbol', 10)->notNull()->comment('Cryptocurrency symbol (BTC, ETH, etc.)');
$table->decimal('quantity', 20, 8)->notNull()->comment('Quantity of cryptocurrency owned');
$table->decimal('avg_buy_price', 15, 2)->nullable()->comment('Average purchase price in EUR');
$table->timestamp('created_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->timestamp('updated_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->primaryKey('id');
$table->index(['user_id']);
$table->index(['crypto_symbol']);
$table->compositeIndex(['user_id', 'crypto_symbol'], 'idx_user_crypto');
});
}
public function down(): void
{
$this->dropTable('crypto_portfolio');
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
use App\Core\Database\Migration;
/**
* Create dashboard widgets system
*
* Migration to create tables for modular dashboard widgets system
* allowing users to customize their dashboard with module-specific widgets.
*/
class CreateDashboardWidgetsSystem extends Migration
{
/**
* Run the migration
*/
public function up(): void
{
// Create dashboard_widgets table - Available widgets from modules
$this->createTable('dashboard_widgets', function($table) {
$table->bigInteger('id')->autoIncrement()->notNull()
->string('widget_id', 100)->notNull()->comment('Unique widget identifier')
->string('module_name', 100)->notNull()->comment('Module that provides this widget')
->string('widget_name', 255)->notNull()->comment('Display name of widget')
->text('widget_description')->nullable()->comment('Widget description')
->string('widget_class', 255)->notNull()->comment('PHP class that renders the widget')
->string('widget_method', 100)->default('render')->comment('Method to call for rendering')
->json('default_config')->nullable()->comment('Default widget configuration')
->string('widget_size', 20)->default('medium')->comment('small, medium, large, full')
->string('widget_category', 100)->default('general')->comment('Widget category for organization')
->tinyInteger('is_active')->default(1)->notNull()->comment('1=active, 0=inactive')
->timestamp('created_at')->default('CURRENT_TIMESTAMP')->notNull()
->timestamp('updated_at')->default('CURRENT_TIMESTAMP')->notNull()
->primaryKey('id')
->unique('widget_id')
->index('module_name')
->index('widget_category')
->index('is_active');
});
// Create user_dashboard_widgets table - User's personalized dashboard
$this->createTable('user_dashboard_widgets', function($table) {
$table->bigInteger('id')->autoIncrement()->notNull()
->bigInteger('user_id')->notNull()->comment('User who owns this dashboard configuration')
->string('widget_id', 100)->notNull()->comment('Reference to dashboard_widgets.widget_id')
->integer('position_order')->default(0)->comment('Display order on dashboard')
->string('widget_size', 20)->nullable()->comment('User override for widget size')
->json('widget_config')->nullable()->comment('User-specific widget configuration')
->tinyInteger('is_visible')->default(1)->notNull()->comment('1=visible, 0=hidden')
->timestamp('created_at')->default('CURRENT_TIMESTAMP')->notNull()
->timestamp('updated_at')->default('CURRENT_TIMESTAMP')->notNull()
->primaryKey('id')
->uniqueComposite('uk_user_widget', ['user_id', 'widget_id'])
->index('user_id')
->index('position_order')
->index('is_visible');
});
echo "Created dashboard widgets system tables\n";
}
/**
* Reverse the migration
*/
public function down(): void
{
$this->dropTable('user_dashboard_widgets');
$this->dropTable('dashboard_widgets');
echo "Removed dashboard widgets system tables\n";
}
/**
* Get migration description
*/
public function getDescription(): string
{
return 'Create dashboard widgets system for modular customizable dashboard';
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
class CreateDashboardWidgetsTable extends Migration
{
public function up(): void
{
$this->createTable('dashboard_widgets', function($table) {
$table->bigInteger('id')->autoIncrement()->notNull();
$table->string('widget_id', 100)->notNull()->unique();
$table->string('module_name', 100)->notNull()->index();
$table->string('widget_name', 255)->notNull();
$table->text('widget_description')->nullable();
$table->string('widget_class', 255)->notNull();
$table->string('widget_method', 100)->nullable()->default('render');
$table->json('default_config')->nullable();
$table->string('widget_size', 20)->nullable()->default('medium');
$table->string('widget_category', 100)->nullable()->default('general')->index();
$table->boolean('is_active')->nullable()->default(true)->index();
$table->timestamp('created_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->timestamp('updated_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->bigInteger('user_id')->nullable()->index();
$table->primaryKey('id');
$table->index(['widget_id']);
});
}
public function down(): void
{
$this->dropTable('dashboard_widgets');
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
use App\Core\Database\SchemaBuilder;
/**
* Migration: Create Detection Rules Table
*
* Creates advertising_detection_rules table for configurable brand detection rules.
* This allows brands to define custom detection patterns for URLs, domains, paths, etc.
*/
class CreateDetectionRulesTable extends Migration
{
public function up(): void
{
$this->createTable('advertising_detection_rules', function (SchemaBuilder $table) {
$table->id();
$table->unsignedBigInteger('brand_id')->index()->comment('Foreign key to advertising_brands');
$table->varchar('name', 255)->notNull()->comment('Rule name for identification');
$table->text('description')->nullable()->comment('Rule description');
$table->varchar('rule_type', 50)->notNull()->comment('regex, domain, path, parameter, custom');
$table->text('rule_pattern')->notNull()->comment('regex pattern, domain, path pattern, etc.');
$table->json('rule_conditions')->nullable()->comment('additional conditions');
$table->integer('priority')->default(0)->index()->comment('higher priority = checked first');
$table->boolean('is_active')->default(true)->index()->comment('rule status');
$table->json('extraction_rules')->nullable()->comment('how to extract data from matches');
$table->json('fallback_data')->nullable()->comment('fallback data if no match');
$table->timestamps();
// Foreign key constraints
$table->foreignKey('brand_id', 'advertising_brands', 'id', 'CASCADE', 'CASCADE');
// Indexes for performance
$table->index(['brand_id', 'is_active', 'priority'], 'idx_brand_active_priority');
});
}
public function down(): void
{
$this->schema->dropTable('advertising_detection_rules');
}
}
@@ -0,0 +1,62 @@
<?php
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
/**
* Migration para criar a tabela error_logs
* Sistema unificado de monitorização de erros
*/
class CreateErrorLogsTable extends Migration
{
public function up(): void
{
$this->createTable('error_logs', function($table) {
$table->bigInteger('id')->autoIncrement()->notNull();
$table->string('unique_id', 25)->notNull()->unique();
$table->string('project_name', 100)->notNull()->default('CRM');
$table->string('environment', 50)->notNull()->default('production');
$table->string('error_type', 100)->notNull()->default('LogEntry');
$table->enum('severity', ['debug', 'info', 'warning', 'error', 'critical'])->notNull()->default('info');
$table->text('message')->notNull();
$table->string('file_path', 500)->nullable();
$table->integer('line_number')->nullable();
$table->text('stack_trace')->nullable();
$table->json('context_data')->nullable();
$table->string('user_id', 50)->nullable();
$table->string('session_id', 100)->nullable();
$table->string('request_id', 50)->nullable();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->string('url', 500)->nullable();
$table->string('http_method', 10)->nullable();
$table->json('request_data')->nullable();
$table->json('server_data')->nullable();
$table->integer('occurrences')->notNull()->default(1);
$table->timestamp('first_seen')->default('CURRENT_TIMESTAMP')->notNull();
$table->timestamp('last_seen')->default('CURRENT_TIMESTAMP')->notNull();
$table->enum('status', ['open', 'resolved', 'ignored'])->notNull()->default('open');
$table->string('assigned_to', 100)->nullable();
$table->text('resolution_notes')->nullable();
$table->timestamp('resolved_at')->nullable();
$table->timestamp('created_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->timestamp('updated_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->primaryKey('id');
// Índices para performance
$table->index('severity');
$table->index('status');
$table->index('project_name');
$table->index('environment');
$table->index('created_at');
$table->index('unique_id');
});
}
public function down(): void
{
$this->dropTable('error_logs');
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
class CreateInvoicesTable extends Migration
{
/**
* The name of the database connection to use.
* Uses default CRM database for invoices
*/
protected ?string $connection = null; // CRM database (default)
public function up(): void
{
$this->createTable('invoices', function($table) {
$table->bigInteger('id')->autoIncrement()->notNull();
$table->string('invoice_number', 50)->notNull()->unique();
$table->string('customer_name', 255)->notNull();
$table->string('customer_email', 255)->nullable();
$table->decimal('amount', 10, 2)->notNull();
$table->decimal('tax_amount', 10, 2)->default(0.00)->notNull();
$table->decimal('total_amount', 10, 2)->notNull();
$table->enum('status', ['draft', 'pending', 'paid', 'cancelled', 'refunded'])->default('draft')->notNull();
$table->enum('currency', ['EUR', 'USD', 'GBP'])->default('EUR')->notNull();
$table->date('due_date')->nullable();
$table->date('paid_date')->nullable();
$table->text('notes')->nullable();
$table->json('items')->nullable(); // Array de itens da fatura
$table->string('payment_method', 100)->nullable();
$table->string('payment_reference', 255)->nullable();
$table->bigInteger('created_by')->nullable();
$table->timestamp('created_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->timestamp('updated_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->timestamp('deleted_at')->nullable();
$table->primaryKey('id');
$table->index(['status', 'due_date']);
$table->index(['customer_email']);
$table->index(['created_by']);
});
}
public function down(): void
{
$this->dropTable('invoices');
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
/**
* Create Landing Templates Table
*
* Tabela para gerir templates de landing por marca/país
* 1 template = 1 imagem por marca/país = Infinitos trackers
*/
class CreateLandingTemplatesTable extends Migration
{
protected ?string $connection = null;
public function up(): void
{
$this->db->query("
CREATE TABLE IF NOT EXISTS advertising_landing_templates (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
cuid VARCHAR(64) NOT NULL UNIQUE,
brand_id BIGINT(20) UNSIGNED NOT NULL,
country_code VARCHAR(10) NOT NULL,
template_type VARCHAR(50) NOT NULL DEFAULT 'banner',
image_path VARCHAR(500) NOT NULL,
mobile_image_path VARCHAR(500) NULL,
desktop_image_path VARCHAR(500) NULL,
is_active TINYINT(1) NOT NULL DEFAULT 1,
created_by BIGINT(20) NOT NULL DEFAULT 1,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at TIMESTAMP NULL,
PRIMARY KEY (id),
INDEX idx_brand_country (brand_id, country_code),
INDEX idx_template_type (template_type),
INDEX idx_is_active (is_active),
INDEX idx_created_by (created_by),
INDEX idx_deleted_at (deleted_at),
FOREIGN KEY (brand_id) REFERENCES advertising_brands(id) ON DELETE CASCADE,
UNIQUE KEY unique_brand_country_type (brand_id, country_code, template_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
}
public function down(): void
{
$this->db->query("DROP TABLE IF EXISTS advertising_landing_templates");
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
class CreateRevenueTable extends Migration
{
public function up(): void
{
$this->createTable('revenue', function($table) {
$table->bigInteger('id')->autoIncrement()->notNull();
$table->decimal('amount', 10, 2)->default(0.00)->notNull()->comment('Revenue amount');
$table->string('source', 100)->nullable()->comment('Revenue source');
$table->string('category', 100)->nullable()->comment('Revenue category');
$table->text('description')->nullable()->comment('Revenue description');
$table->tinyInteger('status')->default(1)->notNull()->comment('0=inactive, 1=active, -1=deleted');
$table->timestamp('created_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->timestamp('updated_at')->default('CURRENT_TIMESTAMP')->notNull();
$table->primaryKey('id');
$table->index(['status']);
$table->index(['created_at']);
$table->index(['source']);
$table->index(['category']);
$table->compositeIndex(['status', 'created_at'], 'idx_status_date');
});
}
public function down(): void
{
$this->dropTable('revenue');
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
use App\Core\Database\SchemaBuilder;
class ExpandSiteGroupsStatusToVarchar extends Migration
{
public function up(): void
{
$this->log("🔄 Converting site groups status from ENUM to VARCHAR for Google Sheets integration");
// Convert status from ENUM to VARCHAR(50) to support all Google Sheets status values
// Following project preference for VARCHAR over ENUM as documented in DATABASE_SOFT_DELETE_GUIDE.md
$sql = "ALTER TABLE advertising_site_groups
MODIFY COLUMN status VARCHAR(50) NOT NULL DEFAULT 'active'";
$this->db->query($sql);
$this->log("✅ Site groups status converted to VARCHAR(50) successfully");
$this->log("📝 Now supports all Google Sheets status values without ENUM limitations");
}
public function down(): void
{
$this->log("🔄 Reverting site groups status to original ENUM values");
// First, update any non-standard status values to 'inactive'
$this->db->query("UPDATE advertising_site_groups
SET status = 'inactive'
WHERE status NOT IN ('active', 'inactive', 'pending')");
// Revert to original enum (though project prefers VARCHAR)
$sql = "ALTER TABLE advertising_site_groups
MODIFY COLUMN status ENUM('active','inactive','pending')
NOT NULL DEFAULT 'active'";
$this->db->query($sql);
$this->log("✅ Site groups status reverted to original ENUM (not recommended)");
}
public function getDescription(): string
{
return "Convert site groups status from ENUM to VARCHAR(50) for Google Sheets integration";
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Core\Database\Migrations;
use App\Core\Database\Migration;
class RemoveLegacyTrackersTable extends Migration
{
protected ?string $connection = null;
public function up(): void
{
// Remove legacy trackers table that was not being used
// This table had only 3 columns (id, url, created_at) and 0 records
// All tracker functionality uses advertising_trackers table instead
$this->db->query("DROP TABLE IF EXISTS trackers");
}
public function down(): void
{
// Recreate the legacy table if needed (though it was unused)
$this->db->query("
CREATE TABLE IF NOT EXISTS trackers (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
url TEXT NOT NULL,
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
}
}
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Core\Database;
use App\Core\Database;
use App\Core\Logger;
use Closure;
class SchemaManager
{
private Database $db;
private Logger $logger;
public function __construct(Database $db, Logger $logger)
{
$this->db = $db;
$this->logger = $logger;
}
public function create(string $tableName, Closure $callback): void
{
$builder = new SchemaBuilder($tableName);
$callback($builder);
$sql = $builder->getSql();
try {
$this->db->execute($sql);
$this->logger->info("Tabela {$tableName} criada com sucesso", ['table' => $tableName]);
} catch (\Exception $e) {
$this->logger->error("Erro ao criar tabela {$tableName}", ['error' => $e->getMessage(), 'sql' => $sql]);
throw $e;
}
}
public function dropIfExists(string $tableName): void
{
$sql = "DROP TABLE IF EXISTS `{$tableName}`;";
try {
$this->db->execute($sql);
$this->logger->info("Tabela {$tableName} eliminada com sucesso", ['table' => $tableName]);
} catch (\Exception $e) {
$this->logger->error("Erro ao eliminar tabela {$tableName}", ['error' => $e->getMessage()]);
throw $e;
}
}
}
+811
View File
@@ -0,0 +1,811 @@
<?php
declare(strict_types=1);
namespace App\Core;
use PDO;
use PDOException;
use Exception;
/**
* DatabaseManager - Centralized database management system
* Implements singleton pattern and methods for all database operations
*/
class DatabaseManager
{
private PDO $pdo;
private static ?self $instance = null;
private string $currentDatabase;
private string $currentProfile = 'default';
/**
* Multi-connection: allows multiple PDO connections per host/user/db
*/
private static array $_connections = [];
/**
* Connection profiles configuration
*/
private static array $connectionProfiles = [];
private function __construct()
{
$this->loadConnectionProfiles();
$this->pdo = $this->createConnection();
$this->currentDatabase = $_ENV['DB_NAME'] ?? 'crm';
}
/**
* Create PDO connection
*/
private function createConnection(): PDO
{
try {
// Load environment variables
\App\Core\EnvironmentLoader::load();
$config = \App\Core\EnvironmentLoader::getDatabaseConfig();
// In local development, use MAMP socket
if ($config['host'] === 'localhost' && $config['port'] === '8889') {
$dsn = "mysql:unix_socket=" . ($config['socket'] ?: '/Applications/MAMP/tmp/mysql/mysql.sock') . ";dbname=" . $config['database'];
} else {
$dsn = "mysql:host=" . $config['host'] .
";dbname=" . $config['database'] .
";port=" . $config['port'];
// Add socket if defined
if (!empty($config['socket'])) {
$dsn .= ";unix_socket=" . $config['socket'];
}
}
return new PDO(
$dsn,
$config['username'],
$config['password'],
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . $config['charset']
]
);
} catch (PDOException $e) {
// ErrorReporter::report($e, ['context' => 'Database connection creation']);
throw new Exception("Database connection failed: " . $e->getMessage());
}
}
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Get PDO connection (compatibility method)
*/
public static function getConnection(): PDO
{
return self::getInstance()->pdo;
}
/**
* Switch to a specific database
*/
public function useDatabase(string $database): bool
{
try {
// Create new PDO connection with specified database
$host = $_ENV['DB_HOST'] ?? 'localhost';
$port = $_ENV['DB_PORT'] ?? '8889';
$user = $_ENV['DB_USER'] ?? 'root';
$pass = $_ENV['DB_PASS'] ?? 'root';
// In local development, use MAMP socket
if ($host === '127.0.0.1' && $port === '8889') {
$dsn = "mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname={$database}";
} else {
$dsn = "mysql:host={$host};dbname={$database};port={$port}";
// Add socket if defined
if (isset($_ENV['DB_SOCKET']) && !empty($_ENV['DB_SOCKET'])) {
$dsn .= ";unix_socket=" . $_ENV['DB_SOCKET'];
}
}
$this->pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
]);
$this->currentDatabase = $database;
return true;
} catch (PDOException $e) {
// ErrorReporter::report($e, ['context' => 'Database switch', 'database' => $database]);
return false;
}
}
/**
* Get current database name
*/
public function getCurrentDatabase(): string
{
return $this->currentDatabase;
}
/**
* Switch back to default database
*/
public function useDefaultDatabase(): bool
{
$defaultDb = $_ENV['DB_NAME'] ?? 'crm';
return $this->useDatabase($defaultDb);
}
/**
* Execute query on specific database
*/
public function queryOnDatabase(string $database, string $query, array $params = []): mixed
{
$originalDb = $this->currentDatabase;
$this->useDatabase($database);
try {
$result = $this->query($query, $params);
return $result;
} finally {
$this->useDatabase($originalDb);
}
}
/**
* Fetch single record from specific database
*/
public function fetchOnDatabase(string $database, string $query, array $params = [], ?callable $callback = null): ?array
{
$originalDb = $this->currentDatabase;
$this->useDatabase($database);
try {
$result = $this->fetch($query, $params, $callback);
return $result;
} finally {
$this->useDatabase($originalDb);
}
}
/**
* Fetch all records from specific database
*/
public function fetchAllOnDatabase(string $database, string $query, array $params = [], ?callable $callback = null): array
{
$originalDb = $this->currentDatabase;
$this->useDatabase($database);
try {
$result = $this->fetchAll($query, $params, $callback);
return $result;
} finally {
$this->useDatabase($originalDb);
}
}
/**
* Fetch a single record
*/
public function fetch(string $query, array $params = [], ?callable $callback = null): ?array
{
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
$result = $stmt->fetch();
if ($callback && $result) {
$result = $callback($result);
}
return $result ?: null;
} catch (PDOException $e) {
$this->logError($e, $query, $params);
throw new Exception("Database fetch error: " . $e->getMessage());
}
}
/**
* Fetch all records
*/
public function fetchAll(string $query, array $params = [], ?callable $callback = null): array
{
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
$results = $stmt->fetchAll();
if ($callback) {
$results = array_map($callback, $results);
}
return $results;
} catch (PDOException $e) {
$this->logError($e, $query, $params);
throw new Exception("Database fetchAll error: " . $e->getMessage());
}
}
/**
* Execute INSERT, UPDATE, DELETE query
*/
public function query(string $query, array $params = []): int
{
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
return $stmt->rowCount();
} catch (PDOException $e) {
$this->logError($e, $query, $params);
throw new Exception("Database query error: " . $e->getMessage());
}
}
/**
* Execute raw SQL (use with caution)
*/
public function execute(string $sql): bool
{
try {
return $this->pdo->exec($sql) !== false;
} catch (PDOException $e) {
ErrorReporter::report($e, ['context' => 'Raw SQL execution', 'sql' => $sql]);
throw new Exception("Database execute error: " . $e->getMessage());
}
}
/**
* Execute query and return results
*/
public function queryWithResult(string $sql, array $params = []): array
{
try {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return [
'rowCount' => $stmt->rowCount(),
'lastInsertId' => $this->pdo->lastInsertId(),
'results' => $stmt->fetchAll()
];
} catch (PDOException $e) {
$this->logError($e, $sql, $params);
throw new Exception("Database queryWithResult error: " . $e->getMessage());
}
}
/**
* Insert or update record based on unique keys
*/
public function insertOrUpdate(string $table, array $data, array $uniqueKeys = ['id']): int
{
try {
// Check if record exists
$whereConditions = [];
$whereParams = [];
foreach ($uniqueKeys as $key) {
if (isset($data[$key])) {
$whereConditions[] = "{$key} = ?";
$whereParams[] = $data[$key];
}
}
if (empty($whereConditions)) {
throw new Exception("No unique keys provided for insertOrUpdate");
}
$whereClause = implode(' AND ', $whereConditions);
$existing = $this->fetch("SELECT COUNT(*) as count FROM {$table} WHERE {$whereClause}", $whereParams);
if ($existing && $existing['count'] > 0) {
// Update existing record
return $this->update($table, $data, array_combine($uniqueKeys, $whereParams));
} else {
// Insert new record
return $this->insert($table, $data);
}
} catch (Exception $e) {
ErrorReporter::report($e, ['context' => 'InsertOrUpdate', 'table' => $table, 'data' => $data]);
throw $e;
}
}
/**
* Insert new record
*/
public function insert(string $table, array $data): int
{
try {
$columns = implode(', ', array_keys($data));
$placeholders = '?' . str_repeat(', ?', count($data) - 1);
$sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
$stmt = $this->pdo->prepare($sql);
$stmt->execute(array_values($data));
return (int) $this->pdo->lastInsertId();
} catch (PDOException $e) {
$this->logError($e, "INSERT INTO {$table}", $data);
throw new Exception("Database insert error: " . $e->getMessage());
}
}
/**
* Update existing record
*/
public function update(string $table, array $data, array $where): int
{
try {
$setParts = [];
$whereParts = [];
$params = [];
// Build SET clause
foreach ($data as $column => $value) {
$setParts[] = "{$column} = ?";
$params[] = $value;
}
// Build WHERE clause
foreach ($where as $column => $value) {
$whereParts[] = "{$column} = ?";
$params[] = $value;
}
$setClause = implode(', ', $setParts);
$whereClause = implode(' AND ', $whereParts);
$sql = "UPDATE {$table} SET {$setClause} WHERE {$whereClause}";
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt->rowCount();
} catch (PDOException $e) {
$this->logError($e, "UPDATE {$table}", array_merge($data, $where));
throw new Exception("Database update error: " . $e->getMessage());
}
}
/**
* Delete records
*/
public function delete(string $table, array $where): int
{
try {
$whereParts = [];
$params = [];
foreach ($where as $column => $value) {
$whereParts[] = "{$column} = ?";
$params[] = $value;
}
$whereClause = implode(' AND ', $whereParts);
$sql = "DELETE FROM {$table} WHERE {$whereClause}";
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt->rowCount();
} catch (PDOException $e) {
$this->logError($e, "DELETE FROM {$table}", $where);
throw new Exception("Database delete error: " . $e->getMessage());
}
}
/**
* Count records
*/
public function count(string $table, array $where = []): int
{
try {
$sql = "SELECT COUNT(*) as count FROM {$table}";
$params = [];
if (!empty($where)) {
$whereParts = [];
foreach ($where as $column => $value) {
$whereParts[] = "{$column} = ?";
$params[] = $value;
}
$sql .= " WHERE " . implode(' AND ', $whereParts);
}
$result = $this->fetch($sql, $params);
return (int) ($result['count'] ?? 0);
} catch (PDOException $e) {
$this->logError($e, "COUNT {$table}", $where);
throw new Exception("Database count error: " . $e->getMessage());
}
}
/**
* Check if record exists
*/
public function exists(string $table, array $where): bool
{
return $this->count($table, $where) > 0;
}
/**
* Execute transaction
*/
public function transaction(callable $callback): mixed
{
try {
$this->pdo->beginTransaction();
$result = $callback($this);
$this->pdo->commit();
return $result;
} catch (Exception $e) {
$this->pdo->rollBack();
throw $e;
}
}
/**
* Get last insert ID
*/
public function lastInsertId(): int
{
return (int) $this->pdo->lastInsertId();
}
/**
* Log database errors
*/
private function logError(PDOException $e, string $query, array $params): void
{
// ErrorReporter::report($e, [
// 'context' => 'Database operation',
// 'query' => $query,
// 'params' => $params,
// 'database' => $this->currentDatabase
// ]);
}
/**
* Get PDO instance (use with caution)
*/
public function getPDO(): PDO
{
return $this->pdo;
}
// Prevent cloning
private function __clone() {}
/**
* Prevent unserialization
*/
public function __wakeup()
{
throw new Exception("Cannot unserialize singleton");
}
/**
* Get connection for specific database
*/
public static function getConnectionFor(string $database, ?string $host = null, ?string $user = null, ?string $pass = null, ?string $port = null): PDO
{
$connectionKey = "{$host}:{$port}:{$user}:{$database}";
if (!isset(self::$_connections[$connectionKey])) {
$host = $host ?? $_ENV['DB_HOST'] ?? 'localhost';
$port = $port ?? $_ENV['DB_PORT'] ?? '8889';
$user = $user ?? $_ENV['DB_USER'] ?? 'root';
$pass = $pass ?? $_ENV['DB_PASS'] ?? 'root';
// In local development, use MAMP socket
if ($host === '127.0.0.1' && $port === '8889') {
$dsn = "mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname={$database}";
} else {
$dsn = "mysql:host={$host};dbname={$database};port={$port}";
// Add socket if defined
if (isset($_ENV['DB_SOCKET']) && !empty($_ENV['DB_SOCKET'])) {
$dsn .= ";unix_socket=" . $_ENV['DB_SOCKET'];
}
}
try {
self::$_connections[$connectionKey] = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
]);
} catch (PDOException $e) {
// ErrorReporter::report($e, [
// 'context' => 'Multi-connection creation',
// 'database' => $database,
// 'host' => $host,
// 'port' => $port
// ]);
throw new Exception("Failed to create connection for database {$database}: " . $e->getMessage());
}
}
return self::$_connections[$connectionKey];
}
/**
* Escape value for safe use in queries
*/
public function escape($value): string
{
if (is_null($value)) {
return 'NULL';
}
if (is_bool($value)) {
return $value ? '1' : '0';
}
if (is_numeric($value)) {
return (string) $value;
}
return $this->pdo->quote($value);
}
/**
* Extract JSON field value
*/
public function jsonExtract(string $field, string $key): string
{
return "JSON_EXTRACT({$field}, '$.{$key}')";
}
/**
* Execute query with retry mechanism
*/
private function queryWithRetry(string $query, array $params = [], int $maxRetries = 3): int|array
{
$attempts = 0;
$lastException = null;
while ($attempts < $maxRetries) {
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
// Determine if it's a SELECT or other query
if (stripos(trim($query), 'SELECT') === 0) {
return $stmt->fetchAll();
} else {
return $stmt->rowCount();
}
} catch (PDOException $e) {
$lastException = $e;
$attempts++;
// Only retry on connection-related errors
if ($e->getCode() !== 'HY000' || strpos($e->getMessage(), 'server has gone away') === false) {
break;
}
// Wait before retry (exponential backoff)
if ($attempts < $maxRetries) {
sleep(pow(2, $attempts));
}
}
}
// If we get here, all retries failed
$this->logError($lastException, $query, $params);
throw new Exception("Database query failed after {$maxRetries} attempts: " . $lastException->getMessage());
}
/**
* Fetch all records with flexible error handling
*/
public function fetchAllFlexible(string $query, array $params = [], ?callable $callback = null): array
{
try {
return $this->fetchAll($query, $params, $callback);
} catch (Exception $e) {
// ErrorReporter::report($e, ['context' => 'Flexible fetchAll', 'query' => $query]);
return [];
}
}
/**
* Fetch single record with flexible error handling
*/
public function fetchFlexible(string $query, array $params = [], ?callable $callback = null): ?array
{
try {
return $this->fetch($query, $params, $callback);
} catch (Exception $e) {
// ErrorReporter::report($e, ['context' => 'Flexible fetch', 'query' => $query]);
return null;
}
}
/**
* Safe insert or update with error handling
*/
public function insertOrUpdateSafe(string $table, array $data, array $uniqueKeys = ['id']): int
{
try {
return $this->insertOrUpdate($table, $data, $uniqueKeys);
} catch (Exception $e) {
ErrorReporter::report($e, ['context' => 'Safe insertOrUpdate', 'table' => $table]);
return 0;
}
}
/**
* Load connection profiles from environment variables
*/
private function loadConnectionProfiles(): void
{
if (!empty(self::$connectionProfiles)) {
return; // Already loaded
}
// Load environment first
\App\Core\EnvironmentLoader::load();
// Try to get profiles as string first (new format)
$profilesString = \App\Core\EnvironmentLoader::get('DB_PROFILES');
if (!empty($profilesString)) {
// Parse comma-separated profiles
$profiles = explode(',', $profilesString);
foreach ($profiles as $profile) {
$profile = trim($profile);
if (empty($profile)) continue;
// Parse profile format: name:host:port:user:pass:db:charset:socket
$parts = explode(':', $profile);
if (count($parts) < 5) continue; // Need at least name, host, port, user, pass, db
$profileName = trim($parts[0]);
$config = [];
if (count($parts) >= 2) $config['host'] = trim($parts[1]);
if (count($parts) >= 3) $config['port'] = trim($parts[2]);
if (count($parts) >= 4) $config['username'] = trim($parts[3]);
if (count($parts) >= 5) $config['password'] = trim($parts[4]);
if (count($parts) >= 6) $config['database'] = trim($parts[5]);
if (count($parts) >= 7) $config['charset'] = trim($parts[6]);
if (count($parts) >= 8) $config['socket'] = trim($parts[7]);
self::$connectionProfiles[$profileName] = $config;
}
} else {
// New format with prefixes: DB_PROFILE_DEFAULT, DB_PROFILE_IMPORTER, etc.
$prefixProfiles = [
'default' => $_ENV['DB_PROFILE_DEFAULT'] ?? null,
'importer' => $_ENV['DB_PROFILE_IMPORTER'] ?? null,
'legacy' => $_ENV['DB_PROFILE_LEGACY'] ?? null,
];
foreach ($prefixProfiles as $profileName => $profileConfig) {
if (empty($profileConfig)) continue;
$config = [];
$parts = explode(':', $profileConfig);
if (count($parts) >= 1) $config['host'] = trim($parts[0]);
if (count($parts) >= 2) $config['port'] = trim($parts[1]);
if (count($parts) >= 3) $config['username'] = trim($parts[2]);
if (count($parts) >= 4) $config['password'] = trim($parts[3]);
if (count($parts) >= 5) $config['database'] = trim($parts[4]);
if (count($parts) >= 6) $config['charset'] = trim($parts[5]);
if (count($parts) >= 7) $config['socket'] = trim($parts[6]);
self::$connectionProfiles[$profileName] = $config;
}
}
}
/**
* Get configuration for a specific connection profile
*/
public static function getConnectionProfile(string $profileName = 'default'): array
{
if (!isset(self::$connectionProfiles[$profileName])) {
throw new Exception("Connection profile '{$profileName}' not found.");
}
return self::$connectionProfiles[$profileName];
}
/**
* Switch to a different connection profile
*/
public function connectionProfile(string $profileName): self
{
if ($this->currentProfile === $profileName) {
return $this; // Already using this profile
}
$this->currentProfile = $profileName;
$this->pdo = $this->createConnectionForProfile($profileName);
return $this;
}
/**
* Create connection for specific profile
*/
private function createConnectionForProfile(string $profileName): PDO
{
try {
// Load environment variables
\App\Core\EnvironmentLoader::load();
$defaultConfig = \App\Core\EnvironmentLoader::getDatabaseConfig();
// Get profile-specific config
$profileConfig = self::getConnectionProfile($profileName);
// Merge default config with profile config
$config = array_merge($defaultConfig, $profileConfig);
// Create connection key for caching
$connectionKey = "{$profileName}:{$config['host']}:{$config['port']}:{$config['database']}:{$config['username']}";
// Check if connection already exists
if (isset(self::$_connections[$connectionKey])) {
return self::$_connections[$connectionKey];
}
// In local development, use MAMP socket
if ($config['host'] === 'localhost' && $config['port'] === '8889') {
$dsn = "mysql:unix_socket=" . ($config['socket'] ?: '/Applications/MAMP/tmp/mysql/mysql.sock') . ";dbname=" . $config['database'];
} else {
$dsn = "mysql:host=" . $config['host'] .
";dbname=" . $config['database'] .
";port=" . $config['port'];
// Add socket if defined
if (!empty($config['socket'])) {
$dsn .= ";unix_socket=" . $config['socket'];
}
}
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_TIMEOUT => 5, // 5 seconds timeout
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . ($config['charset'] ?: 'utf8mb4')
];
$pdo = new PDO($dsn, $config['username'], $config['password'], $options);
// Cache the connection
self::$_connections[$connectionKey] = $pdo;
return $pdo;
} catch (PDOException $e) {
throw new Exception("Database connection failed for profile '{$profileName}': " . $e->getMessage());
}
}
/**
* Get current connection profile name
*/
public function getCurrentProfile(): string
{
return $this->currentProfile;
}
/**
* List all available connection profiles
*/
public static function getAvailableProfiles(): array
{
return array_keys(self::$connectionProfiles);
}
}
+322
View File
@@ -0,0 +1,322 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Environment Loader
*
* Loads environment variables from config.env file into $_ENV superglobal.
* Ensures consistent environment configuration across web and CLI contexts.
*/
class EnvironmentLoader
{
private static bool $loaded = false;
private static array $config = [];
private static string $cacheFile = '';
private static int $lastModified = 0;
/**
* Load environment variables from config.env with caching
*/
public static function load(): void
{
$configFile = dirname(__DIR__, 2) . '/.env';
self::$cacheFile = dirname(__DIR__, 2) . '/storage/cache/env_cache.php';
if (!file_exists($configFile)) {
throw new \RuntimeException("Configuration file not found: {$configFile}");
}
$configModified = filemtime($configFile);
// Check if we can use cached version
if (self::$loaded && self::$lastModified === $configModified) {
return; // Already loaded and file hasn't changed
}
// Try to load from cache if it exists and is newer than config file
if (self::loadFromCache($configModified)) {
self::$loaded = true;
self::$lastModified = $configModified;
return;
}
// Parse config file and create cache
self::parseConfigFile($configFile);
self::saveToCache($configModified);
self::$loaded = true;
self::$lastModified = $configModified;
}
/**
* Get environment variable with optional default
*/
public static function get(string $key, $default = null)
{
self::load();
return $_ENV[$key] ?? $default;
}
/**
* Get all environment variables
*/
public static function all(): array
{
self::load();
return self::$config;
}
/**
* Check if environment variable exists
*/
public static function has(string $key): bool
{
self::load();
return isset($_ENV[$key]);
}
/**
* Get database configuration array
*/
public static function getDatabaseConfig(): array
{
self::load();
return [
'host' => $_ENV['DB_HOST'] ?? 'localhost',
'port' => $_ENV['DB_PORT'] ?? '3306',
'database' => $_ENV['DB_NAME'] ?? 'crm',
'username' => $_ENV['DB_USER'] ?? 'root',
'password' => $_ENV['DB_PASS'] ?? '',
'socket' => $_ENV['DB_SOCKET'] ?? null,
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
];
}
/**
* Reset loaded state (for testing)
*/
public static function reset(): void
{
self::$loaded = false;
self::$config = [];
}
/**
* Convert profile arrays to comma-separated string format
*/
private static function convertArrayToString(string $key, array $value): string
{
if ($key === 'DB_PROFILES') {
$profiles = [];
foreach ($value as $profileName => $profileConfig) {
$profiles[] = $profileName . ':' . $profileConfig;
}
return implode(',', $profiles);
}
// For other arrays, just join with commas
return implode(',', $value);
}
/**
* Get array configuration (for direct access to arrays)
*/
public static function getArray(string $key): array
{
self::load();
return self::$config[$key] ?? [];
}
/**
* Try to load configuration from cache
*/
private static function loadFromCache(int $configModified): bool
{
if (!file_exists(self::$cacheFile)) {
return false;
}
$cacheModified = filemtime(self::$cacheFile);
// Cache is older than config file
if ($cacheModified < $configModified) {
return false;
}
try {
$cached = include self::$cacheFile;
if (!is_array($cached) || !isset($cached['config']) || !isset($cached['timestamp'])) {
return false;
}
// Verify cache timestamp matches config file
if ($cached['timestamp'] !== $configModified) {
return false;
}
self::$config = $cached['config'];
// Load into $_ENV superglobal
self::loadIntoEnvironment();
return true;
} catch (\Exception $e) {
// Cache file is corrupted, ignore and reparse
return false;
}
}
/**
* Save configuration to cache
*/
private static function saveToCache(int $configModified): void
{
try {
// Ensure cache directory exists
$cacheDir = dirname(self::$cacheFile);
if (!is_dir($cacheDir)) {
mkdir($cacheDir, 0755, true);
}
$cacheContent = "<?php\n// Auto-generated environment cache - DO NOT EDIT\n";
$cacheContent .= "// Generated: " . date('Y-m-d H:i:s') . "\n";
$cacheContent .= "// Config file modified: " . date('Y-m-d H:i:s', $configModified) . "\n\n";
$cacheContent .= "return " . var_export([
'timestamp' => $configModified,
'config' => self::$config
], true) . ";\n";
file_put_contents(self::$cacheFile, $cacheContent, LOCK_EX);
} catch (\Exception $e) {
// Cache save failed, but don't break the application
// Just continue without cache
}
}
/**
* Parse the config file (extracted from original load method)
*/
private static function parseConfigFile(string $configFile): void
{
// Read and parse file manually to handle comments better
$lines = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
self::$config = [];
foreach ($lines as $line) {
$line = trim($line);
// Skip comments and empty lines
if (empty($line) || $line[0] === '#') {
continue;
}
// Parse key=value pairs
if (strpos($line, '=') !== false) {
[$key, $value] = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
// Remove quotes if present
if (in_array($value[0] ?? '', ['"', "'"])) {
$value = substr($value, 1, -1);
}
// Handle array syntax: KEY[index] = value
if (preg_match('/^([A-Z_]+)\[([^\]]+)\]$/', $key, $matches)) {
$arrayKey = $matches[1];
$index = $matches[2];
if (!isset(self::$config[$arrayKey])) {
self::$config[$arrayKey] = [];
}
self::$config[$arrayKey][$index] = $value;
} else {
self::$config[$key] = $value;
}
}
}
// Load into environment
self::loadIntoEnvironment();
}
/**
* Load configuration into $_ENV and $_SERVER
*/
private static function loadIntoEnvironment(): void
{
foreach (self::$config as $key => $value) {
if (is_array($value)) {
// Convert arrays to comma-separated string for backward compatibility
$_ENV[$key] = self::convertArrayToString($key, $value);
$_SERVER[$key] = $_ENV[$key];
// Also set individual array items as separate env vars
foreach ($value as $arrayKey => $arrayValue) {
$_ENV["{$key}_{$arrayKey}"] = $arrayValue;
$_SERVER["{$key}_{$arrayKey}"] = $arrayValue;
}
} else {
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}
}
/**
* Clear environment cache (useful for development)
*/
public static function clearCache(): bool
{
self::$cacheFile = self::$cacheFile ?: dirname(__DIR__, 2) . '/storage/cache/env_cache.php';
if (file_exists(self::$cacheFile)) {
return unlink(self::$cacheFile);
}
return true;
}
/**
* Get cache information for debugging
*/
public static function getCacheInfo(): array
{
$configFile = dirname(__DIR__, 2) . '/.env';
self::$cacheFile = self::$cacheFile ?: dirname(__DIR__, 2) . '/storage/cache/env_cache.php';
$info = [
'config_file' => $configFile,
'config_exists' => file_exists($configFile),
'config_modified' => file_exists($configFile) ? date('Y-m-d H:i:s', filemtime($configFile)) : null,
'cache_file' => self::$cacheFile,
'cache_exists' => file_exists(self::$cacheFile),
'cache_modified' => file_exists(self::$cacheFile) ? date('Y-m-d H:i:s', filemtime(self::$cacheFile)) : null,
'loaded' => self::$loaded,
'last_modified' => self::$lastModified,
'using_cache' => file_exists(self::$cacheFile) && file_exists($configFile) && filemtime(self::$cacheFile) >= filemtime($configFile)
];
return $info;
}
/**
* Force reload (bypass cache)
*/
public static function forceReload(): void
{
self::$loaded = false;
self::$lastModified = 0;
self::$config = [];
self::load();
}
}
+305
View File
@@ -0,0 +1,305 @@
<?php
declare(strict_types=1);
namespace App\Core;
use Exception;
use Throwable;
/**
* ErrorReporter - Sistema centralizado de reporte de erros
* Implementa logging e tratamento de erros conforme as regras do projeto
*/
class ErrorReporter
{
private static ?Logger $logger = null;
private static ?AlertManager $alertManager = null;
private static array $errorCounts = [];
private static int $maxErrorsPerMinute = 10;
/**
* Reportar erro/exception
*/
public static function report(Throwable $exception, array $context = []): void
{
try {
// Log simples para evitar loops infinitos
error_log("ErrorReporter: " . $exception->getMessage() . " in " . $exception->getFile() . ":" . $exception->getLine());
// Mostrar erro visual em desenvolvimento/localhost
self::displayErrorIfDebug($exception, $context);
// Desativar temporariamente o sistema completo para evitar loops
// self::logError($exception, $context);
// self::captureWithErrorMonitoring($exception, $context);
// self::checkErrorThreshold($exception);
// self::notifyIfCritical($exception, $context);
} catch (Throwable $e) {
// Fallback para evitar loops infinitos
error_log("ErrorReporter failed: " . $e->getMessage());
}
}
/**
* Mostrar erro visual em desenvolvimento/localhost
*/
private static function displayErrorIfDebug(Throwable $exception, array $context = []): void
{
// Verificar se deve mostrar erro visual
$showDebug = false;
// Verificar variável de ambiente
if (($_ENV['APP_DEBUG'] ?? false) === true) {
$showDebug = true;
}
// Verificar parâmetro de URL
if (isset($_GET['view_errors']) && $_GET['view_errors'] === 'true') {
$showDebug = true;
}
// Verificar se é localhost
if (isset($_SERVER['HTTP_HOST']) && strpos($_SERVER['HTTP_HOST'], 'localhost') !== false) {
$showDebug = true;
}
if (!$showDebug) {
return;
}
// Verificar se já foi enviado output
if (headers_sent()) {
return;
}
// Definir status code
http_response_code(500);
// Mostrar erro detalhado
echo '<h1>500 Internal Server Error</h1>';
echo '<pre style="background: #f5f5f5; padding: 15px; border: 1px solid #ddd; border-radius: 4px; font-family: monospace; font-size: 12px;">';
echo '<strong>Error:</strong> ' . htmlspecialchars($exception->getMessage()) . "\n\n";
echo '<strong>File:</strong> ' . htmlspecialchars($exception->getFile()) . "\n";
echo '<strong>Line:</strong> ' . htmlspecialchars((string)$exception->getLine()) . "\n\n";
if (!empty($context)) {
echo '<strong>Context:</strong> ' . htmlspecialchars(json_encode($context, JSON_PRETTY_PRINT)) . "\n\n";
}
echo '<strong>Stack Trace:</strong>' . "\n";
echo htmlspecialchars($exception->getTraceAsString());
echo '</pre>';
// Parar execução em modo debug
if ($showDebug) {
exit;
}
}
/**
* Capturar erro com o novo sistema de monitorização
*/
private static function captureWithErrorMonitoring(Throwable $exception, array $context = []): void
{
try {
// Verificar se o módulo ErrorMonitoring está disponível
if (class_exists('\App\Modules\ErrorMonitoring\Services\ErrorCollector')) {
$collector = \App\Modules\ErrorMonitoring\Services\ErrorCollector::getInstance();
// Determinar ambiente
$environment = defined('APP_ENV') ? constant('APP_ENV') : 'production';
if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], 'localhost') !== false) {
$environment = 'development';
}
$collector->setEnvironment($environment)
->addContext('error_reporter_context', $context)
->capture($exception, $context);
}
} catch (Throwable $e) {
// Silenciar erros do sistema de monitorização para não criar loops
error_log("ErrorMonitoring capture failed: " . $e->getMessage());
}
}
/**
* Reportar erro simples
*/
public static function error(string $message, array $context = []): void
{
$exception = new Exception($message);
self::report($exception, $context);
}
/**
* Reportar warning
*/
public static function warning(string $message, array $context = []): void
{
self::getLogger()->warning($message, $context);
}
/**
* Reportar info
*/
public static function info(string $message, array $context = []): void
{
self::getLogger()->info($message, $context);
}
/**
* Log de erro detalhado
*/
private static function logError(Throwable $exception, array $context = []): void
{
$logger = self::getLogger();
$logData = [
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTraceAsString(),
'context' => $context,
'timestamp' => date('Y-m-d H:i:s'),
'user_id' => $_SESSION['user_id'] ?? null,
'request_uri' => $_SERVER['REQUEST_URI'] ?? null,
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
'ip' => $_SERVER['REMOTE_ADDR'] ?? null
];
$logger->error("Exception: " . $exception->getMessage(), $logData);
}
/**
* Verificar threshold de erros
*/
private static function checkErrorThreshold(Throwable $exception): void
{
$minute = date('Y-m-d H:i');
$errorKey = $exception->getMessage();
if (!isset(self::$errorCounts[$minute])) {
self::$errorCounts[$minute] = [];
}
if (!isset(self::$errorCounts[$minute][$errorKey])) {
self::$errorCounts[$minute][$errorKey] = 0;
}
self::$errorCounts[$minute][$errorKey]++;
// Limpar dados antigos (mais de 1 hora)
$oldMinute = date('Y-m-d H:i', strtotime('-1 hour'));
unset(self::$errorCounts[$oldMinute]);
// Alertar se muitos erros
if (self::$errorCounts[$minute][$errorKey] >= self::$maxErrorsPerMinute) {
self::getAlertManager()->createAlert(
'error_threshold',
'Muitos erros detectados',
"Erro '{$errorKey}' ocorreu " . self::$errorCounts[$minute][$errorKey] . " vezes no último minuto",
'high'
);
}
}
/**
* Notificar se erro crítico
*/
private static function notifyIfCritical(Throwable $exception, array $context = []): void
{
$criticalPatterns = [
'database connection',
'fatal error',
'memory limit',
'timeout',
'permission denied'
];
$message = strtolower($exception->getMessage());
foreach ($criticalPatterns as $pattern) {
if (strpos($message, $pattern) !== false) {
self::getAlertManager()->createAlert(
'critical_error',
'Erro Crítico Detectado',
$exception->getMessage(),
'critical',
$context
);
break;
}
}
}
/**
* Obter instância do Logger
*/
private static function getLogger(): ?Logger
{
if (self::$logger === null) {
try {
self::$logger = new Logger();
} catch (\Exception $e) {
// Fallback para evitar loops infinitos
error_log("Failed to create Logger: " . $e->getMessage());
return null;
}
}
return self::$logger;
}
/**
* Obter instância do AlertManager
*/
private static function getAlertManager(): AlertManager
{
if (self::$alertManager === null) {
self::$alertManager = new AlertManager();
}
return self::$alertManager;
}
/**
* Definir logger customizado
*/
public static function setLogger(Logger $logger): void
{
self::$logger = $logger;
}
/**
* Definir alert manager customizado
*/
public static function setAlertManager(AlertManager $alertManager): void
{
self::$alertManager = $alertManager;
}
/**
* Definir threshold de erros
*/
public static function setMaxErrorsPerMinute(int $max): void
{
self::$maxErrorsPerMinute = $max;
}
/**
* Obter estatísticas de erros
*/
public static function getErrorStats(): array
{
return [
'current_minute' => self::$errorCounts[date('Y-m-d H:i')] ?? [],
'total_errors' => array_sum(array_map('array_sum', self::$errorCounts))
];
}
/**
* Limpar estatísticas
*/
public static function clearStats(): void
{
self::$errorCounts = [];
}
}
+313
View File
@@ -0,0 +1,313 @@
<?php
namespace App\Core;
use App\Core\InputSanitizer;
use App\Core\Sanitize;
/**
* FilterManager - Sistema centralizado de filtros para todos os módulos
*
* Fornece métodos padronizados para:
* - Sanitização de inputs
* - Validação de filtros
* - Construção de queries SQL
* - Paginação
* - Ordenação
*/
class FilterManager
{
private array $allowedFilters = [];
private array $filterDefaults = [];
private array $sortFieldMapping = [];
private array $allowedSortFields = [];
public function __construct(array $config = [])
{
$this->allowedFilters = $config['allowed_filters'] ?? [];
$this->filterDefaults = $config['filter_defaults'] ?? [];
$this->sortFieldMapping = $config['sort_field_mapping'] ?? [];
$this->allowedSortFields = $config['allowed_sort_fields'] ?? [];
}
/**
* Processa todos os filtros de uma vez
*/
public function processFilters(array $customDefaults = []): array
{
$filters = array_merge($this->filterDefaults, $customDefaults);
foreach ($this->allowedFilters as $filterName => $config) {
$value = $this->getFilterValue($filterName, $config);
if ($value !== null) {
$filters[$filterName] = $value;
}
}
return $filters;
}
/**
* Obtém valor de um filtro específico com validação
*/
public function getFilterValue(string $filterName, array $config): mixed
{
$method = $config['method'] ?? 'GET';
$type = $config['type'] ?? 'string';
$default = $config['default'] ?? null;
$validation = $config['validation'] ?? null;
$value = InputSanitizer::get($filterName, $method);
// Se não há valor, retornar default
if ($value === null) {
return $default;
}
// Sanitizar baseado no tipo
$value = $this->sanitizeValue($value, $type);
// Aplicar validação se especificada
if ($validation && !$this->validateValue($value, $validation)) {
return $default;
}
return $value;
}
/**
* Sanitiza valor baseado no tipo
*/
private function sanitizeValue(mixed $value, string $type): mixed
{
return match($type) {
'integer' => Sanitize::integer($value),
'float', 'decimal' => Sanitize::decimal($value),
'boolean' => Sanitize::boolean($value),
'array' => is_array($value) ? array_filter($value) : array_filter(explode(',', $value)),
'string' => Sanitize::string($value),
'email' => Sanitize::email($value),
'url' => Sanitize::url($value),
default => $value
};
}
/**
* Valida valor baseado nas regras especificadas
*/
private function validateValue(mixed $value, array $validation): bool
{
foreach ($validation as $rule => $params) {
if (!$this->applyValidationRule($value, $rule, $params)) {
return false;
}
}
return true;
}
/**
* Aplica regra de validação específica
*/
private function applyValidationRule(mixed $value, string $rule, mixed $params): bool
{
return match($rule) {
'min_length' => strlen($value) >= $params,
'max_length' => strlen($value) <= $params,
'min_value' => $value >= $params,
'max_value' => $value <= $params,
'in_array' => in_array($value, $params),
'regex' => preg_match($params, $value),
'required' => !empty($value),
default => true
};
}
/**
* Processa paginação
*/
public function processPagination(array $defaults = []): array
{
$page = max(1, Sanitize::integer(InputSanitizer::get('page', 'GET') ?? 1));
$limit = max(1, min(1000, Sanitize::integer(InputSanitizer::get('limit', 'GET') ?? 20)));
$offset = ($page - 1) * $limit;
return array_merge($defaults, [
'page' => $page,
'limit' => $limit,
'offset' => $offset
]);
}
/**
* Processa ordenação
*/
public function processSorting(array $defaults = []): array
{
$sortBy = Sanitize::string(InputSanitizer::get('sort', 'GET') ?? 'last_update');
$sortOrder = Sanitize::string(InputSanitizer::get('order', 'GET') ?? 'DESC');
// Validar campo de ordenação
if (!empty($this->allowedSortFields) && !in_array($sortBy, $this->allowedSortFields)) {
$sortBy = $defaults['sort_by'] ?? 'last_update';
}
// Validar direção
$sortOrder = strtoupper($sortOrder) === 'DESC' ? 'DESC' : 'ASC';
// Mapear para campo real da base de dados
$orderByField = $this->sortFieldMapping[$sortBy] ?? $sortBy;
return array_merge($defaults, [
'sort_by' => $sortBy,
'sort_order' => $sortOrder,
'order_by_field' => $orderByField
]);
}
/**
* Constrói WHERE clause para SQL
*/
public function buildWhereClause(array $filters, string $baseWhere = ''): array
{
$whereClause = $baseWhere ?: 'WHERE 1=1';
$params = [];
foreach ($filters as $field => $value) {
if ($value === null || $value === '') {
continue;
}
$condition = $this->buildCondition($field, $value);
if ($condition) {
$whereClause .= " AND " . $condition['clause'];
$params = array_merge($params, $condition['params']);
}
}
return [
'where' => $whereClause,
'params' => $params
];
}
/**
* Constrói condição SQL para um campo
*/
private function buildCondition(string $field, mixed $value): ?array
{
if (is_array($value)) {
if (empty($value)) return null;
$placeholders = str_repeat('?,', count($value) - 1) . '?';
return [
'clause' => "$field IN ($placeholders)",
'params' => $value
];
}
if (is_string($value) && str_contains($value, '%')) {
return [
'clause' => "$field LIKE ?",
'params' => [$value]
];
}
return [
'clause' => "$field = ?",
'params' => [$value]
];
}
/**
* Configura filtros permitidos
*/
public function setAllowedFilters(array $filters): self
{
$this->allowedFilters = $filters;
return $this;
}
/**
* Configura mapeamento de campos de ordenação
*/
public function setSortFieldMapping(array $mapping): self
{
$this->sortFieldMapping = $mapping;
return $this;
}
/**
* Configura campos de ordenação permitidos
*/
public function setAllowedSortFields(array $fields): self
{
$this->allowedSortFields = $fields;
return $this;
}
/**
* Factory method para criar FilterManager para Ecommerce
*/
public static function createForEcommerce(): self
{
return new self([
'allowed_filters' => [
'search' => [
'type' => 'string',
'validation' => ['max_length' => 100]
],
'ean' => [
'type' => 'string',
'validation' => ['max_length' => 50]
],
'family_id' => [
'type' => 'array',
'validation' => ['min_value' => 1]
],
'brand_id' => [
'type' => 'array',
'validation' => ['min_value' => 1]
],
'supplier_id' => [
'type' => 'array',
'validation' => ['min_value' => 1]
],
'stock_min' => [
'type' => 'integer',
'validation' => ['min_value' => 0]
],
'price_min' => [
'type' => 'float',
'validation' => ['min_value' => 0]
],
'price_max' => [
'type' => 'float',
'validation' => ['min_value' => 0]
],
'onlySelected' => [
'type' => 'boolean'
]
],
'filter_defaults' => [
'page' => 1,
'limit' => 20,
'sort_by' => 'last_update',
'sort_order' => 'DESC'
],
'allowed_sort_fields' => [
'ean', 'name', 'brand_name', 'price', 'price_with_vat',
'stock', 'supplier_name', 'published_status', 'last_update'
],
'sort_field_mapping' => [
'ean' => 'p.ean',
'name' => 'p.name',
'brand_name' => 'b.brand',
'price' => 'p.price',
'price_with_vat' => '(p.price * 1.23)',
'stock' => 'p.stock',
'supplier_name' => 's.name',
'published_status' => 'ps1.u_site',
'last_update' => 'p.last_update'
]
]);
}
}
+160
View File
@@ -0,0 +1,160 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* InputSanitizer - Sanitização automática de todos os inputs
* Implementa sanitização defensiva universal para $_POST, $_GET, $_REQUEST
*/
class InputSanitizer
{
private static array $sanitizedInputs = [];
private static bool $initialized = false;
/**
* Inicializar sanitização automática
*/
public static function initialize(): void
{
if (self::$initialized) {
return;
}
// Process JSON input for API requests
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (strpos($contentType, 'application/json') !== false) {
$jsonInput = file_get_contents('php://input');
$jsonData = json_decode($jsonInput, true);
if ($jsonData && is_array($jsonData)) {
foreach ($jsonData as $key => $value) {
self::$sanitizedInputs['POST'][$key] = self::sanitizeValue($value);
}
}
}
// Sanitizar $_POST
foreach ($_POST as $key => $value) {
self::$sanitizedInputs['POST'][$key] = self::sanitizeValue($value);
}
// Sanitizar $_GET
foreach ($_GET as $key => $value) {
self::$sanitizedInputs['GET'][$key] = self::sanitizeValue($value);
}
// Sanitizar $_REQUEST
foreach ($_REQUEST as $key => $value) {
self::$sanitizedInputs['REQUEST'][$key] = self::sanitizeValue($value);
}
self::$initialized = true;
}
/**
* Obter input sanitizado
*/
public static function get(string $key, string $method = 'POST', $default = ''): mixed
{
self::initialize();
return self::$sanitizedInputs[$method][$key] ?? $default;
}
/**
* Obter todos os inputs sanitizados de um método
*/
public static function all(string $method = 'POST'): array
{
self::initialize();
return self::$sanitizedInputs[$method] ?? [];
}
/**
* Verificar se input existe
*/
public static function has(string $key, string $method = 'POST'): bool
{
self::initialize();
return isset(self::$sanitizedInputs[$method][$key]);
}
/**
* Sanitizar valor baseado no tipo
*/
private static function sanitizeValue($value): mixed
{
if (is_array($value)) {
return array_map([self::class, 'sanitizeValue'], $value);
}
if (is_string($value)) {
return Sanitize::string($value);
}
if (is_numeric($value)) {
return Sanitize::integer($value);
}
return $value;
}
/**
* Sanitizar input específico com tipo
*/
public static function email(string $key, string $method = 'POST'): string
{
$value = self::get($key, $method);
return Sanitize::email($value);
}
public static function integer(string $key, string $method = 'POST', ?int $min = null, ?int $max = null): int
{
$value = self::get($key, $method);
return Sanitize::integer($value, $min, $max);
}
public static function decimal(string $key, string $method = 'POST', int $decimals = 2): float
{
$value = self::get($key, $method);
return Sanitize::decimal($value, $decimals);
}
public static function url(string $key, string $method = 'POST'): string
{
$value = self::get($key, $method);
return Sanitize::url($value);
}
public static function phone(string $key, string $method = 'POST'): string
{
$value = self::get($key, $method);
return Sanitize::phone($value);
}
public static function date(string $key, string $method = 'POST'): string
{
$value = self::get($key, $method);
return Sanitize::date($value);
}
/**
* Validar input com regras
*/
public static function validate(string $key, array $rules, string $method = 'POST'): array
{
$value = self::get($key, $method);
return Validate::rules($value, $rules);
}
/**
* Limpar dados sanitizados
*/
public static function clear(): void
{
self::$sanitizedInputs = [];
self::$initialized = false;
}
}
+582
View File
@@ -0,0 +1,582 @@
<?php
declare(strict_types=1);
namespace App\Core;
use App\Core\DatabaseManager;
/**
* Logger Inteligente - Otimizado para Performance
*
* - Ficheiros pequenos (1MB max)
* - Processamento automático para MySQL
* - Limpeza automática
* - Sem processamento em memória PHP
*/
class Logger
{
private string $logPath;
private DatabaseManager $db;
private const MAX_FILE_SIZE = 1024 * 1024; // 1MB
private const MAX_LINES_PER_FILE = 1000;
public function __construct()
{
$this->logPath = __DIR__ . '/../../storage/logs/';
// Desativar temporariamente o DatabaseManager para evitar loops
// $this->db = DatabaseManager::getInstance();
// Criar diretório se não existir
if (!is_dir($this->logPath)) {
mkdir($this->logPath, 0755, true);
}
}
/**
* Log inteligente - escreve em ficheiros pequenos e move para error_logs
*/
public function log(string $level, string $message, array $context = []): void
{
// Desativar temporariamente o logging para evitar crescimento de ficheiros
// $date = date('Y-m-d');
// $filename = "{$this->logPath}{$level}-{$date}.log";
// // Verificar se ficheiro está muito grande OU se é de um dia anterior
// $shouldProcess = false;
// $reason = '';
// if (file_exists($filename)) {
// $fileSize = filesize($filename);
// $fileAge = time() - filemtime($filename);
// if ($fileSize > self::MAX_FILE_SIZE) {
// $shouldProcess = true;
// $reason = 'size_limit';
// } elseif ($fileAge > 3600) { // 1 hora
// $shouldProcess = true;
// $reason = 'age_limit';
// }
// }
// if ($shouldProcess) {
// // NÃO processar automaticamente - será feito via API separada
// // Apenas apagar ficheiro se for muito antigo (> 24h)
// if (($fileAge ?? 0) > 24 * 3600) {
// unlink($filename);
// // Log do processamento automático
// $this->log('info', "Ficheiro antigo removido: {$filename}", [
// 'reason' => $reason,
// 'file_size' => $this->formatBytes($fileSize ?? 0),
// 'file_age_hours' => round(($fileAge ?? 0) / 3600, 1),
// 'level' => $level
// ]);
// }
// }
// // Escrever nova entrada
// $logEntry = [
// 'timestamp' => date('Y-m-d H:i:s'),
// 'level' => $level,
// 'message' => $message,
// 'context' => $context
// ];
// $line = json_encode($logEntry) . PHP_EOL;
// file_put_contents($filename, $line, FILE_APPEND | LOCK_EX);
// Log simples para evitar crescimento de ficheiros
error_log("Logger[{$level}]: {$message}");
}
/**
* Processar ficheiro para tabela error_logs (estrutura rica)
*/
public function processFileToErrorLogs(string $filename, string $level): int
{
if (!file_exists($filename)) {
return 0;
}
try {
$this->createErrorLogsTable();
$handle = fopen($filename, 'r');
if (!$handle) {
return 0;
}
$linesProcessed = 0;
$batch = [];
$batchSize = 50;
while (($line = fgets($handle)) !== false) {
$data = json_decode(trim($line), true);
if ($data) {
$errorData = $this->formatLogEntryForErrorLogs($data, $level);
$batch[] = $errorData;
if (count($batch) >= $batchSize) {
$this->insertErrorLogsBatch($batch);
$linesProcessed += count($batch);
$batch = [];
}
}
}
// Inserir batch final
if (!empty($batch)) {
$this->insertErrorLogsBatch($batch);
$linesProcessed += count($batch);
}
fclose($handle);
// Apagar ficheiro após processamento bem-sucedido
if ($linesProcessed > 0 && file_exists($filename)) {
unlink($filename);
}
return $linesProcessed;
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'logger_process_file_to_error_logs',
'filename' => $filename,
'level' => $level
]);
return 0;
}
}
/**
* Formatar entrada de log para estrutura error_logs
*/
private function formatLogEntryForErrorLogs(array $data, string $level): array
{
$context = $data['context'] ?? [];
return [
'unique_id' => $this->generateUniqueId(),
'project_name' => $context['project_name'] ?? 'CRM',
'environment' => $context['environment'] ?? 'production',
'error_type' => $context['error_type'] ?? 'LogEntry',
'severity' => $this->mapLevelToSeverity($level),
'message' => substr($data['message'] ?? '', 0, 1000),
'file_path' => $context['file_path'] ?? '',
'line_number' => $context['line_number'] ?? 0,
'stack_trace' => $context['stack_trace'] ?? '',
'context_data' => json_encode($context),
'user_id' => $context['user_id'] ?? '',
'session_id' => $context['session_id'] ?? '',
'request_id' => $context['request_id'] ?? '',
'ip_address' => $context['ip_address'] ?? '',
'user_agent' => $context['user_agent'] ?? '',
'url' => $context['url'] ?? '',
'http_method' => $context['http_method'] ?? '',
'request_data' => json_encode($context['request_data'] ?? []),
'server_data' => json_encode($context['server_data'] ?? []),
'occurrences' => 1,
'first_seen' => $data['timestamp'] ?? date('Y-m-d H:i:s'),
'last_seen' => $data['timestamp'] ?? date('Y-m-d H:i:s'),
'status' => 'open',
'assigned_to' => '',
'resolution_notes' => '',
'resolved_at' => null,
'created_at' => $data['timestamp'] ?? date('Y-m-d H:i:s'),
'updated_at' => $data['timestamp'] ?? date('Y-m-d H:i:s')
];
}
/**
* Mapear nível de log para severidade
*/
private function mapLevelToSeverity(string $level): string
{
switch (strtolower($level)) {
case 'critical':
case 'emergency':
return 'critical';
case 'error':
return 'error';
case 'warning':
return 'warning';
case 'info':
return 'info';
case 'debug':
return 'debug';
default:
return 'info';
}
}
/**
* Gerar ID único
*/
private function generateUniqueId(): string
{
return strtoupper(substr(md5(uniqid() . microtime()), 0, 25));
}
/**
* Inserir batch de logs na tabela error_logs
*/
private function insertErrorLogsBatch(array $batch): void
{
if (empty($batch)) return;
$values = [];
$params = [];
foreach ($batch as $log) {
$values[] = "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$params = array_merge($params, [
$log['unique_id'],
$log['project_name'],
$log['environment'],
$log['error_type'],
$log['severity'],
$log['message'],
$log['file_path'],
$log['line_number'],
$log['stack_trace'],
$log['context_data'],
$log['user_id'],
$log['session_id'],
$log['request_id'],
$log['ip_address'],
$log['user_agent'],
$log['url'],
$log['http_method'],
$log['request_data'],
$log['server_data'],
$log['occurrences'],
$log['first_seen'],
$log['last_seen'],
$log['status'],
$log['assigned_to'],
$log['resolution_notes'],
$log['resolved_at'],
$log['created_at'],
$log['updated_at']
]);
}
$sql = "INSERT INTO error_logs (
unique_id, project_name, environment, error_type, severity, message,
file_path, line_number, stack_trace, context_data, user_id, session_id,
request_id, ip_address, user_agent, url, http_method, request_data,
server_data, occurrences, first_seen, last_seen, status, assigned_to,
resolution_notes, resolved_at, created_at, updated_at
) VALUES " . implode(', ', $values);
$this->db->query($sql, $params);
}
/**
* Criar tabela error_logs se não existir
*/
private function createErrorLogsTable(): void
{
$sql = "CREATE TABLE IF NOT EXISTS error_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
unique_id VARCHAR(25) NOT NULL UNIQUE,
project_name VARCHAR(100) NOT NULL DEFAULT 'CRM',
environment VARCHAR(50) NOT NULL DEFAULT 'production',
error_type VARCHAR(100) NOT NULL DEFAULT 'LogEntry',
severity ENUM('debug', 'info', 'warning', 'error', 'critical') NOT NULL DEFAULT 'info',
message TEXT NOT NULL,
file_path VARCHAR(500),
line_number INT,
stack_trace TEXT,
context_data JSON,
user_id VARCHAR(50),
session_id VARCHAR(100),
request_id VARCHAR(50),
ip_address VARCHAR(45),
user_agent TEXT,
url VARCHAR(500),
http_method VARCHAR(10),
request_data JSON,
server_data JSON,
occurrences INT NOT NULL DEFAULT 1,
first_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status ENUM('open', 'resolved', 'ignored') NOT NULL DEFAULT 'open',
assigned_to VARCHAR(100),
resolution_notes TEXT,
resolved_at TIMESTAMP NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_severity (severity),
INDEX idx_status (status),
INDEX idx_project (project_name),
INDEX idx_environment (environment),
INDEX idx_created_at (created_at),
INDEX idx_unique_id (unique_id)
)";
$this->db->query($sql);
}
/**
* Obter estatísticas dos logs
*/
public function getStats(): array
{
try {
// Estatísticas dos ficheiros
$files = glob($this->logPath . '*.log');
$totalFiles = count($files);
$totalSize = 0;
foreach ($files as $file) {
if (file_exists($file)) {
$totalSize += filesize($file);
}
}
// Estatísticas da base de dados (error_logs)
$totalLogsInDb = 0;
$levels = [];
try {
$sql = "SELECT
COUNT(*) as total,
severity,
COUNT(CASE WHEN status = 'open' THEN 1 END) as open_count,
COUNT(CASE WHEN status = 'resolved' THEN 1 END) as resolved_count
FROM error_logs
GROUP BY severity";
$results = $this->db->fetchAll($sql);
foreach ($results as $row) {
$totalLogsInDb += $row['total'];
$levels[$row['severity']] = [
'total' => $row['total'],
'open' => $row['open_count'],
'resolved' => $row['resolved_count']
];
}
// Se não há resultados, tentar contar total
if ($totalLogsInDb === 0) {
$countResult = $this->db->fetch("SELECT COUNT(*) as total FROM error_logs");
$totalLogsInDb = $countResult['total'] ?? 0;
}
} catch (\Exception $e) {
// Tabela pode não existir ainda
$totalLogsInDb = 0;
}
// Logs recentes (limitados para performance)
$recentEntries = [];
try {
$sql = "SELECT severity, message, created_at
FROM error_logs
ORDER BY created_at DESC
LIMIT 5";
$recentResults = $this->db->fetchAll($sql);
foreach ($recentResults as $row) {
$recentEntries[] = "[{$row['severity']}] " . substr($row['message'], 0, 100);
}
} catch (\Exception $e) {
// Ignorar se tabela não existir
}
return [
'total_files' => $totalFiles,
'total_size' => $totalSize,
'total_size_formatted' => $this->formatBytes($totalSize),
'total_logs_in_db' => $totalLogsInDb,
'levels' => $levels,
'recent_entries' => $recentEntries,
'status' => 'unified_system'
];
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'logger_get_stats']);
return [
'total_files' => 0,
'total_size' => 0,
'total_size_formatted' => '0 B',
'total_logs_in_db' => 0,
'levels' => [],
'recent_entries' => [],
'status' => 'error'
];
}
}
/**
* Limpeza automática (apenas ficheiros antigos)
*/
public function cleanup(int $daysToKeep = 7): int
{
$files = glob($this->logPath . '*.log');
$deletedCount = 0;
$maxAge = $daysToKeep * 24 * 60 * 60;
foreach ($files as $file) {
if (file_exists($file) && (time() - filemtime($file)) > $maxAge) {
// NÃO processar automaticamente - será feito via API separada
// Apenas apagar ficheiro antigo
unlink($file);
$deletedCount++;
}
}
return $deletedCount;
}
/**
* Processamento inteligente - só processa se necessário
* Retorna estatísticas do que foi processado
*/
public function processIfNeeded(): array
{
$files = glob($this->logPath . '*.log');
$processed = false;
$filesProcessed = 0;
$filesSkipped = 0;
$totalLinesProcessed = 0;
$reason = 'no_files_to_process';
if (empty($files)) {
return [
'processed' => false,
'files_processed' => 0,
'files_skipped' => 0,
'total_lines_processed' => 0,
'reason' => 'no_files_found'
];
}
foreach ($files as $file) {
if (!file_exists($file)) continue;
$fileSize = filesize($file);
$fileAge = time() - filemtime($file);
$maxAge = 30 * 60; // 30 minutos (mais agressivo)
// Processar se: ficheiro > 1MB OU ficheiro > 30min OU ficheiro > 100KB
$shouldProcess = false;
$processReason = '';
if ($fileSize > self::MAX_FILE_SIZE) {
$shouldProcess = true;
$processReason = 'size_large';
} elseif ($fileAge > $maxAge) {
$shouldProcess = true;
$processReason = 'age_old';
} elseif ($fileSize > 100 * 1024) { // 100KB
$shouldProcess = true;
$processReason = 'size_medium';
}
if ($shouldProcess) {
// NÃO processar automaticamente - será feito via API separada
// Apenas marcar como processado se ficheiro for muito antigo
if ($fileAge > 24 * 3600) { // 24 horas
unlink($file);
$filesProcessed++;
$processed = true;
// Log do processamento
$this->log('info', "Ficheiro antigo removido: {$file}", [
'file_size' => $this->formatBytes($fileSize),
'file_age_minutes' => round($fileAge / 60, 1),
'level' => $this->extractLevelFromFilename($file),
'reason' => $processReason
]);
} else {
$filesSkipped++;
}
} else {
$filesSkipped++;
}
}
return [
'processed' => $processed,
'files_processed' => $filesProcessed,
'files_skipped' => $filesSkipped,
'total_lines_processed' => $totalLinesProcessed,
'reason' => $processed ? 'files_processed' : 'no_files_need_processing'
];
}
/**
* Processar todos os ficheiros grandes
*/
public function processAllLargeFiles(): array
{
$files = glob($this->logPath . '*.log');
$filesProcessed = 0;
$totalLinesProcessed = 0;
$errors = [];
foreach ($files as $file) {
if (!file_exists($file)) continue;
$fileSize = filesize($file);
// NÃO processar automaticamente - será feito via API separada
// Apenas marcar ficheiro grande para processamento posterior
if ($fileSize > self::MAX_FILE_SIZE) {
$filesProcessed++;
// Log do ficheiro grande encontrado
$this->log('info', "Ficheiro grande encontrado (não processado): {$file}", [
'file_size' => $this->formatBytes($fileSize),
'level' => $this->extractLevelFromFilename($file)
]);
}
}
return [
'files_processed' => $filesProcessed,
'total_lines_processed' => $totalLinesProcessed,
'errors' => $errors
];
}
/**
* Extrair nível de log do nome do ficheiro
*/
private function extractLevelFromFilename(string $filename): string
{
$basename = basename($filename);
$parts = explode('-', $basename);
return $parts[0] ?? 'info';
}
/**
* Formatar bytes para legibilidade
*/
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, 2) . ' ' . $units[$pow];
}
// Métodos de conveniência
public function emergency(string $message, array $context = []): void { $this->log('emergency', $message, $context); }
public function alert(string $message, array $context = []): void { $this->log('alert', $message, $context); }
public function critical(string $message, array $context = []): void { $this->log('critical', $message, $context); }
public function error(string $message, array $context = []): void { $this->log('error', $message, $context); }
public function warning(string $message, array $context = []): void { $this->log('warning', $message, $context); }
public function notice(string $message, array $context = []): void { $this->log('notice', $message, $context); }
public function info(string $message, array $context = []): void { $this->log('info', $message, $context); }
public function debug(string $message, array $context = []): void { $this->log('debug', $message, $context); }
}
+185
View File
@@ -0,0 +1,185 @@
<?php
declare(strict_types=1);
namespace App\Core;
class MenuManager
{
private static array $registeredMenus = [];
private static bool $initialized = false;
/**
* Registar um item de menu para um módulo
*/
public static function registerMenu(string $module, array $menuItem): void
{
if (!isset(self::$registeredMenus[$module])) {
self::$registeredMenus[$module] = [];
}
self::$registeredMenus[$module][] = $menuItem;
}
/**
* Registar múltiplos itens de menu para um módulo
*/
public static function registerMenus(string $module, array $menuItems): void
{
if (!isset(self::$registeredMenus[$module])) {
self::$registeredMenus[$module] = [];
}
self::$registeredMenus[$module] = array_merge(self::$registeredMenus[$module], $menuItems);
}
/**
* Obter todos os menus registados
*/
public static function getMenus(): array
{
if (!self::$initialized) {
self::loadModuleMenus();
}
return self::$registeredMenus;
}
/**
* Obter menu final organizado hierarquicamente
*/
public static function getFinalMenu(): array
{
if (!self::$initialized) {
self::loadModuleMenus();
}
$allMenus = [];
$isDev = ($_ENV['APP_ENV'] ?? 'production') === 'development';
foreach (self::$registeredMenus as $module => $menus) {
foreach ($menus as $menu) {
// Filtrar por ambiente: se é dev, mostrar tudo; se não é dev, só mostrar menus com dev=0
if ($isDev || ($menu['dev'] ?? 0) === 0) {
$allMenus[] = $menu;
}
}
}
// Organizar hierarquicamente
return self::buildHierarchicalMenu($allMenus);
}
/**
* Carregar menus dos módulos automaticamente
*/
private static function loadModuleMenus(): void
{
$modulesDir = PathManager::getModulesPath();
if (!is_dir($modulesDir)) {
return;
}
// Get current client ID and module config
$clientId = \App\Core\Branding::getClientId();
$moduleConfig = \App\Core\ModuleConfig::getInstance();
// Primeiro, carregar menus das rotas automaticamente
self::loadRouteMenus();
// Depois, carregar menus manuais dos ficheiros menu.php (para compatibilidade)
$moduleFolders = scandir($modulesDir);
foreach ($moduleFolders as $moduleName) {
if ($moduleName[0] === '.') continue;
// Check if module is active for current client
if (!$moduleConfig->isModuleActive($moduleName, $clientId)) {
continue;
}
$menuFile = $modulesDir . '/' . $moduleName . '/menu.php';
if (file_exists($menuFile)) {
require_once $menuFile;
}
}
self::$initialized = true;
}
/**
* Carregar menus das rotas automaticamente
*/
private static function loadRouteMenus(): void
{
// Carregar apenas rotas dos módulos ativos
self::loadModuleRoutes();
// Registar menus das rotas
$router = Router::getInstance();
$router->registerRouteMenus();
}
/**
* Carregar rotas de todos os módulos
*/
private static function loadModuleRoutes(): void
{
$modulesDir = PathManager::getModulesPath();
if (!is_dir($modulesDir)) {
return;
}
// Get current client ID and module config
$clientId = \App\Core\Branding::getClientId();
$moduleConfig = \App\Core\ModuleConfig::getInstance();
$moduleFolders = scandir($modulesDir);
foreach ($moduleFolders as $moduleName) {
if ($moduleName[0] === '.') continue;
// Check if module is active for current client
if (!$moduleConfig->isModuleActive($moduleName, $clientId)) {
continue;
}
// Carregar rotas web
$webRoutesFile = $modulesDir . '/' . $moduleName . '/Routes/web.php';
if (file_exists($webRoutesFile)) {
require_once $webRoutesFile;
}
// Carregar rotas API (normalmente não têm menus, mas pode ser útil)
$apiRoutesFile = $modulesDir . '/' . $moduleName . '/Routes/api.php';
if (file_exists($apiRoutesFile)) {
require_once $apiRoutesFile;
}
}
}
/**
* Construir menu hierárquico
*/
private static function buildHierarchicalMenu(array $menus): array
{
$menuById = [];
$rootMenus = [];
// Indexar por ID
foreach ($menus as $menu) {
$menu['children'] = [];
$menuById[$menu['id']] = $menu;
}
// Construir hierarquia
foreach ($menuById as $id => &$item) {
if (isset($item['parent_id']) && $item['parent_id'] && isset($menuById[$item['parent_id']])) {
$menuById[$item['parent_id']]['children'][] = &$item;
} else {
$rootMenus[] = &$item;
}
}
// Ordenar por ordem
usort($rootMenus, function($a, $b) {
return ($a['order'] ?? 999) - ($b['order'] ?? 999);
});
return $rootMenus;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Core;
class MenuRenderer
{
/**
* Renderiza um menu dinâmico (estrutura recursiva).
* @param array $menu Estrutura do menu.
* @param string $currentUrl URL atual para marcar ativo.
* @param bool $editMode Ativa atributos de edição/drag.
*/
public static function render(array $menu, string $currentUrl, bool $editMode = false): void
{
foreach ($menu as $item) {
$isActive = ($item['url'] === $currentUrl) || (!empty($item['children']) && array_reduce($item['children'], function($carry, $child) use ($currentUrl) { return $carry || ($child['url'] === $currentUrl); }, false));
$hasChildren = !empty($item['children']);
$dragAttr = $editMode ? ' draggable="true" data-menu-id="'.$item['id'].'"' : '';
echo '<li class="nav-item"'.$dragAttr.'>';
echo '<a class="nav-link menu-link'.($isActive ? ' active' : '').($hasChildren ? ' with-submenu' : '').'" href="'.htmlspecialchars($item['url']).'">';
echo '<i class="'.$item['icon'].'"></i> <span>'.htmlspecialchars($item['label']).'</span>';
if ($hasChildren) echo ' <span class="menu-arrow"></span>';
echo '</a>';
if ($hasChildren) {
echo '<ul class="nav nav-sm flex-column submenu'.($isActive ? ' show' : '').'">';
foreach ($item['children'] as $child) {
$childActive = ($child['url'] === $currentUrl);
$childDrag = $editMode ? ' draggable="true" data-menu-id="'.$child['id'].'"' : '';
echo '<li class="nav-item"'.$childDrag.'>';
echo '<a class="nav-link'.($childActive ? ' active' : '').'" href="'.htmlspecialchars($child['url']).'">';
echo '<i class="'.$child['icon'].'"></i> <span>'.htmlspecialchars($child['label']).'</span>';
echo '</a>';
echo '</li>';
}
echo '</ul>';
}
echo '</li>';
}
}
}
+156
View File
@@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Sistema de Configuração Centralizada para Módulos
* Permite configuração isolada e hierárquica
*/
class ModuleConfig
{
private static ?ModuleConfig $instance = null;
private array $configs = [];
private array $moduleConfigs = [];
private function __construct() {}
public static function getInstance(): ModuleConfig
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Carregar configuração de um módulo
*/
public function loadModuleConfig(string $moduleName): void
{
$configPath = PathManager::getModulePath($moduleName) . "/config.php";
if (file_exists($configPath)) {
$this->moduleConfigs[$moduleName] = require $configPath;
} else {
$this->moduleConfigs[$moduleName] = [];
}
}
/**
* Obter configuração de um módulo
*/
public function getModuleConfig(string $moduleName, ?string $key = null, $default = null)
{
if (!isset($this->moduleConfigs[$moduleName])) {
$this->loadModuleConfig($moduleName);
}
if ($key === null) {
return $this->moduleConfigs[$moduleName];
}
return $this->moduleConfigs[$moduleName][$key] ?? $default;
}
/**
* Definir configuração de um módulo
*/
public function setModuleConfig(string $moduleName, string $key, $value): void
{
if (!isset($this->moduleConfigs[$moduleName])) {
$this->moduleConfigs[$moduleName] = [];
}
$this->moduleConfigs[$moduleName][$key] = $value;
}
/**
* Obter configuração global
*/
public function get(string $key, $default = null)
{
return $this->configs[$key] ?? $default;
}
/**
* Definir configuração global
*/
public function set(string $key, $value): void
{
$this->configs[$key] = $value;
}
/**
* Carregar configuração de cliente
*/
public function loadClientConfig(string $clientId): void
{
$configPath = PathManager::getModulesPath() . "/config.php";
if (file_exists($configPath)) {
$config = require $configPath;
$clientConfig = $config['clients'][$clientId] ?? [];
foreach ($clientConfig as $key => $value) {
$this->set($key, $value);
}
}
}
/**
* Verificar se um módulo está ativo para o cliente
*/
public function isModuleActive(string $moduleName, string $clientId): bool
{
$configPath = PathManager::getModulesPath() . "/config.php";
if (file_exists($configPath)) {
$config = require $configPath;
$clientConfig = $config['clients'][$clientId] ?? [];
if (isset($clientConfig['modules'])) {
foreach ($clientConfig['modules'] as $namespace => $modules) {
if (in_array($moduleName, $modules)) {
return true;
}
}
}
}
return false;
}
/**
* Obter lista de módulos ativos para um cliente
*/
public function getActiveModules(string $clientId): array
{
$activeModules = [];
$configPath = PathManager::getModulesPath() . "/config.php";
if (file_exists($configPath)) {
$config = require $configPath;
$clientConfig = $config['clients'][$clientId] ?? [];
if (isset($clientConfig['modules'])) {
foreach ($clientConfig['modules'] as $namespace => $modules) {
foreach ($modules as $module) {
$activeModules[] = "$namespace:$module";
}
}
}
}
return $activeModules;
}
/**
* Limpar todas as configurações
*/
public function clear(): void
{
$this->configs = [];
$this->moduleConfigs = [];
}
}
+191
View File
@@ -0,0 +1,191 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Classe utilitária para sanitização de output
* Centraliza todas as funções de escape e formatação
*/
class OutputSanitize
{
/**
* Escapar HTML para prevenir XSS
*/
public static function html(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
/**
* Escapar atributos HTML
*/
public static function attr(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
/**
* Escapar para JavaScript
*/
public static function js(string $value): string
{
return json_encode($value, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
}
/**
* Escapar para CSS
*/
public static function css(string $value): string
{
return preg_replace('/[^a-zA-Z0-9\-_]/', '', $value);
}
/**
* Escapar para URL
*/
public static function url(string $value): string
{
return urlencode($value);
}
/**
* Formatar data para exibição
*/
public static function date(string $date, string $format = 'd/m/Y'): string
{
if (empty($date)) {
return '';
}
try {
$dateObj = new \DateTime($date);
return $dateObj->format($format);
} catch (\Exception $e) {
return '';
}
}
/**
* Formatar data e hora para exibição
*/
public static function datetime(string $datetime, string $format = 'd/m/Y H:i'): string
{
if (empty($datetime)) {
return '';
}
try {
$dateObj = new \DateTime($datetime);
return $dateObj->format($format);
} catch (\Exception $e) {
return '';
}
}
/**
* Formatar número para exibição
*/
public static function number(float|int $number, int $decimals = 2): string
{
return number_format($number, $decimals, ',', '.');
}
/**
* Formatar moeda para exibição
*/
public static function currency(float|int $amount, string $currency = '€'): string
{
return $currency . ' ' . self::number($amount, 2);
}
/**
* Truncar texto com ellipsis
*/
public static function truncate(string $text, int $length = 100, string $ellipsis = '...'): string
{
if (mb_strlen($text) <= $length) {
return $text;
}
return mb_substr($text, 0, $length) . $ellipsis;
}
/**
* Limpar string para uso em IDs/classes CSS
*/
public static function cssId(string $value): string
{
return preg_replace('/[^a-zA-Z0-9\-_]/', '-', strtolower($value));
}
/**
* Escapar para uso em atributos data-*
*/
public static function dataAttr(string $value): string
{
return self::html($value);
}
/**
* Verificar se valor é vazio e retornar fallback
*/
public static function fallback(string $value, string $fallback = ''): string
{
return empty(trim($value)) ? $fallback : $value;
}
/**
* Formatar bytes para exibição humana
*/
public static function bytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
$bytes /= 1024;
}
return round($bytes, 2) . ' ' . $units[$i];
}
/**
* Formatar percentagem
*/
public static function percentage(float $value, int $decimals = 1): string
{
return number_format($value, $decimals, ',', '.') . '%';
}
/**
* Formatar tempo decorrido
*/
public static function timeAgo(string $datetime): string
{
if (empty($datetime)) {
return '';
}
try {
$date = new \DateTime($datetime);
$now = new \DateTime();
$diff = $now->diff($date);
if ($diff->y > 0) {
return $diff->y . ' ano' . ($diff->y > 1 ? 's' : '');
} elseif ($diff->m > 0) {
return $diff->m . ' mês' . ($diff->m > 1 ? 'es' : '');
} elseif ($diff->d > 0) {
return $diff->d . ' dia' . ($diff->d > 1 ? 's' : '');
} elseif ($diff->h > 0) {
return $diff->h . ' hora' . ($diff->h > 1 ? 's' : '');
} elseif ($diff->i > 0) {
return $diff->i . ' minuto' . ($diff->i > 1 ? 's' : '');
} else {
return 'agora';
}
} catch (\Exception $e) {
return '';
}
}
}
+525
View File
@@ -0,0 +1,525 @@
<?php
declare(strict_types=1);
namespace App\Core;
class PathManager
{
private static ?string $rootPath = null;
private static ?string $appPath = null;
private static ?string $modulesPath = null;
private static ?string $storagePath = null;
private static ?string $publicPath = null;
private static ?string $vendorPath = null;
private static ?string $configPath = null;
private static ?string $docsPath = null;
private static ?string $toolsPath = null;
private static ?string $binPath = null;
/**
* Initialize all paths
*/
public static function initialize(): void
{
if (self::$rootPath !== null) {
return; // Already initialized
}
// Get the root path (where composer.json is located)
self::$rootPath = self::findRootPath();
// Define all other paths relative to root
self::$appPath = self::$rootPath . '/app';
self::$modulesPath = self::$appPath . '/Modules';
self::$storagePath = self::$rootPath . '/storage';
self::$publicPath = self::$rootPath . '/public';
self::$vendorPath = self::$rootPath . '/vendor';
self::$configPath = self::$rootPath . '/config';
self::$docsPath = self::$rootPath . '/docs';
self::$toolsPath = self::$rootPath . '/tools';
self::$binPath = self::$rootPath . '/bin';
}
/**
* Find the project root path by looking for composer.json
*/
private static function findRootPath(): string
{
$currentPath = __DIR__;
// Go up directories until we find composer.json
while ($currentPath !== '/' && $currentPath !== '') {
if (file_exists($currentPath . '/composer.json')) {
return $currentPath;
}
$currentPath = dirname($currentPath);
}
// Fallback to current directory if composer.json not found
return dirname(__DIR__, 3);
}
/**
* Get project root path
*/
public static function getRootPath(): string
{
self::initialize();
return self::$rootPath;
}
/**
* Get app directory path
*/
public static function getAppPath(): string
{
self::initialize();
return self::$appPath;
}
/**
* Get modules directory path
*/
public static function getModulesPath(): string
{
self::initialize();
return self::$modulesPath;
}
/**
* Get storage directory path
*/
public static function getStoragePath(): string
{
self::initialize();
return self::$storagePath;
}
/**
* Get public directory path
*/
public static function getPublicPath(): string
{
self::initialize();
return self::$publicPath;
}
/**
* Get vendor directory path
*/
public static function getVendorPath(): string
{
self::initialize();
return self::$vendorPath;
}
/**
* Get config directory path
*/
public static function getConfigPath(): string
{
self::initialize();
return self::$configPath;
}
/**
* Get docs directory path
*/
public static function getDocsPath(): string
{
self::initialize();
return self::$docsPath;
}
/**
* Get tools directory path
*/
public static function getToolsPath(): string
{
self::initialize();
return self::$toolsPath;
}
/**
* Get bin directory path
*/
public static function getBinPath(): string
{
self::initialize();
return self::$binPath;
}
/**
* Get module path by name
*/
public static function getModulePath(string $moduleName): string
{
return self::getModulesPath() . '/' . $moduleName;
}
/**
* Get module migrations path
*/
public static function getModuleMigrationsPath(string $moduleName): string
{
return self::getModulePath($moduleName) . '/Database/Migrations';
}
/**
* Get module views path
*/
public static function getModuleViewsPath(string $moduleName): string
{
return self::getModulePath($moduleName) . '/Views';
}
/**
* Get module controllers path
*/
public static function getModuleControllersPath(string $moduleName): string
{
return self::getModulePath($moduleName) . '/Controllers';
}
/**
* Get module models path
*/
public static function getModuleModelsPath(string $moduleName): string
{
return self::getModulePath($moduleName) . '/Models';
}
/**
* Get module routes path
*/
public static function getModuleRoutesPath(string $moduleName): string
{
return self::getModulePath($moduleName) . '/Routes';
}
/**
* Get storage logs path
*/
public static function getLogsPath(): string
{
return self::getStoragePath() . '/logs';
}
/**
* Get storage cache path
*/
public static function getCachePath(): string
{
return self::getStoragePath() . '/cache';
}
/**
* Get public assets path
*/
public static function getAssetsPath(): string
{
return self::getPublicPath() . '/assets';
}
/**
* Get public assets CSS path
*/
public static function getAssetsCssPath(): string
{
return self::getAssetsPath() . '/css';
}
/**
* Get public assets JS path
*/
public static function getAssetsJsPath(): string
{
return self::getAssetsPath() . '/js';
}
/**
* Get public assets images path
*/
public static function getAssetsImagesPath(): string
{
return self::getAssetsPath() . '/images';
}
/**
* Get src directory path
*/
public static function getSrcPath(): string
{
return self::getRootPath() . '/src';
}
/**
* Get src JS path
*/
public static function getSrcJsPath(): string
{
return self::getSrcPath() . '/js';
}
/**
* Get src JS Alpine path
*/
public static function getSrcJsAlpinePath(): string
{
return self::getSrcJsPath() . '/alpine';
}
/**
* Get src JS components path
*/
public static function getSrcJsComponentsPath(): string
{
return self::getSrcJsPath() . '/components';
}
/**
* Get src JS pages path
*/
public static function getSrcJsPagesPath(): string
{
return self::getSrcJsPath() . '/pages';
}
/**
* Get src JS modules path
*/
public static function getSrcJsModulesPath(): string
{
return self::getSrcJsPath() . '/modules';
}
/**
* Get src JS utils path
*/
public static function getSrcJsUtilsPath(): string
{
return self::getSrcJsPath() . '/utils';
}
/**
* Get projects directory path
*/
public static function getProjectsPath(): string
{
return self::getRootPath() . '/projects';
}
/**
* Get template directory path
*/
public static function getTemplatePath(): string
{
return self::getRootPath() . '/template';
}
/**
* Get tests directory path
*/
public static function getTestsPath(): string
{
return self::getRootPath() . '/tests';
}
/**
* Get venv directory path
*/
public static function getVenvPath(): string
{
return self::getRootPath() . '/venv_pdu';
}
/**
* Check if path exists
*/
public static function pathExists(string $path): bool
{
return file_exists($path);
}
/**
* Check if path is directory
*/
public static function isDirectory(string $path): bool
{
return is_dir($path);
}
/**
* Check if path is file
*/
public static function isFile(string $path): bool
{
return is_file($path);
}
/**
* Create directory if it doesn't exist
*/
public static function ensureDirectoryExists(string $path): bool
{
if (!self::pathExists($path)) {
return mkdir($path, 0755, true);
}
return true;
}
/**
* Get all module names
*/
public static function getModuleNames(): array
{
$modulesPath = self::getModulesPath();
$modules = [];
if (self::isDirectory($modulesPath)) {
$items = scandir($modulesPath);
foreach ($items as $item) {
if ($item !== '.' && $item !== '..' && self::isDirectory($modulesPath . '/' . $item)) {
$modules[] = $item;
}
}
}
return $modules;
}
/**
* Get all migration files from all modules
*/
public static function getAllMigrationFiles(): array
{
$files = [];
$modules = self::getModuleNames();
foreach ($modules as $module) {
$migrationsPath = self::getModuleMigrationsPath($module);
if (self::isDirectory($migrationsPath)) {
$moduleFiles = glob($migrationsPath . '/*.php');
$files = array_merge($files, $moduleFiles);
}
}
// Remove duplicates and sort
$files = array_unique($files);
sort($files);
return $files;
}
/**
* Get relative path from root
*/
public static function getRelativePath(string $absolutePath): string
{
$rootPath = self::getRootPath();
if (strpos($absolutePath, $rootPath) === 0) {
return substr($absolutePath, strlen($rootPath) + 1);
}
return $absolutePath;
}
/**
* Get absolute path from relative path
*/
public static function getAbsolutePath(string $relativePath): string
{
if (self::isAbsolutePath($relativePath)) {
return $relativePath;
}
return self::getRootPath() . '/' . ltrim($relativePath, '/');
}
/**
* Check if path is absolute
*/
public static function isAbsolutePath(string $path): bool
{
return $path[0] === '/' || (strlen($path) > 1 && $path[1] === ':');
}
/**
* Normalize path (remove double slashes, etc.)
*/
public static function normalizePath(string $path): string
{
return realpath($path) ?: $path;
}
/**
* Get file extension
*/
public static function getFileExtension(string $path): string
{
return pathinfo($path, PATHINFO_EXTENSION);
}
/**
* Get file name without extension
*/
public static function getFileNameWithoutExtension(string $path): string
{
return pathinfo($path, PATHINFO_FILENAME);
}
/**
* Get file name with extension
*/
public static function getFileName(string $path): string
{
return pathinfo($path, PATHINFO_BASENAME);
}
/**
* Get directory name
*/
public static function getDirectoryName(string $path): string
{
return pathinfo($path, PATHINFO_DIRNAME);
}
/**
* Debug: Print all paths
*/
public static function debugPaths(): void
{
self::initialize();
echo "🔍 PathManager Debug Information:\n";
echo "================================\n";
echo "Root Path: " . self::$rootPath . "\n";
echo "App Path: " . self::$appPath . "\n";
echo "Modules Path: " . self::$modulesPath . "\n";
echo "Storage Path: " . self::$storagePath . "\n";
echo "Public Path: " . self::$publicPath . "\n";
echo "Vendor Path: " . self::$vendorPath . "\n";
echo "Config Path: " . self::$configPath . "\n";
echo "Docs Path: " . self::$docsPath . "\n";
echo "Tools Path: " . self::$toolsPath . "\n";
echo "Bin Path: " . self::$binPath . "\n";
echo "Src Path: " . self::getSrcPath() . "\n";
echo "Projects Path: " . self::getProjectsPath() . "\n";
echo "Template Path: " . self::getTemplatePath() . "\n";
echo "Tests Path: " . self::getTestsPath() . "\n";
echo "Venv Path: " . self::getVenvPath() . "\n";
echo "\n";
echo "📁 Available Modules:\n";
$modules = self::getModuleNames();
foreach ($modules as $module) {
echo " - $module\n";
}
echo "\n";
echo "📄 Migration Files Found: " . count(self::getAllMigrationFiles()) . "\n";
}
}
+313
View File
@@ -0,0 +1,313 @@
<?php
declare(strict_types=1);
namespace App\Core;
use App\Core\View;
use App\Core\AuthMiddleware;
use App\Core\MenuManager;
require_once __DIR__ . '/Config/Constants.php';
class Router
{
private static ?self $instance = null;
private array $routes = [];
private array $menuRoutes = []; // Rotas que geram menus automaticamente
private function __construct() {}
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function addRoute(string $method, string $pattern, $handler, array $middleware = [], array $menuConfig = []): void
{
$method = strtoupper($method);
$this->routes[$method][$pattern] = [
'handler' => $handler,
'middleware' => $middleware,
];
// Se tem configuração de menu, registar automaticamente
if (!empty($menuConfig)) {
$this->registerMenuFromRoute($pattern, $menuConfig);
}
}
public function get(string $pattern, $handler, array $middleware = [], array $menuConfig = []): void
{
$this->addRoute('GET', $pattern, $handler, $middleware, $menuConfig);
}
public function post(string $pattern, $handler, array $middleware = [], array $menuConfig = []): void
{
$this->addRoute('POST', $pattern, $handler, $middleware, $menuConfig);
}
public function put(string $pattern, $handler, array $middleware = [], array $menuConfig = []): void
{
$this->addRoute('PUT', $pattern, $handler, $middleware, $menuConfig);
}
public function patch(string $pattern, $handler, array $middleware = [], array $menuConfig = []): void
{
$this->addRoute('PATCH', $pattern, $handler, $middleware, $menuConfig);
}
public function delete(string $pattern, $handler, array $middleware = [], array $menuConfig = []): void
{
$this->addRoute('DELETE', $pattern, $handler, $middleware, $menuConfig);
}
/**
* Registar menu automaticamente baseado na rota
*/
private function registerMenuFromRoute(string $pattern, array $menuConfig): void
{
// Determinar módulo baseado no padrão da rota
$module = $this->extractModuleFromPattern($pattern);
// Configuração padrão do menu
$defaultConfig = [
'url' => $pattern,
'dev' => 0,
'order' => 999
];
// Merge com configuração fornecida
$finalConfig = array_merge($defaultConfig, $menuConfig);
// Guardar para registar posteriormente
$this->menuRoutes[$module][] = $finalConfig;
}
/**
* Extrair nome do módulo baseado no padrão da rota
*/
private function extractModuleFromPattern(string $pattern): string
{
$pathParts = explode('/', trim($pattern, '/'));
// Mapeamento de padrões para módulos
$moduleMapping = [
'crypto' => 'Crypto',
'crm' => 'Crm',
'advertising' => 'Advertising',
'analytics' => 'Analytics',
'users' => 'Users',
'projects' => 'Projects',
'dashboard' => 'Dashboard',
'admin' => 'Admin'
];
if (!empty($pathParts[0]) && isset($moduleMapping[$pathParts[0]])) {
return $moduleMapping[$pathParts[0]];
}
// Fallback para Dashboard se não conseguir determinar
return 'Dashboard';
}
/**
* Registar todos os menus das rotas no MenuManager
*/
public function registerRouteMenus(): void
{
foreach ($this->menuRoutes as $module => $menus) {
foreach ($menus as $menuConfig) {
MenuManager::registerMenu($module, $menuConfig);
}
}
}
/**
* Obter rotas que têm menus configurados
*/
public function getMenuRoutes(): array
{
return $this->menuRoutes;
}
public function getRoutes(): array
{
// Format for listing, compatible with the list_routes script
$formattedRoutes = [];
foreach ($this->routes as $method => $routesByMethod) {
foreach ($routesByMethod as $pattern => $routeData) {
$formattedRoutes[$method][$pattern] = $routeData['handler'];
}
}
return $formattedRoutes;
}
private function preparePattern(string $pattern): string
{
// Suporte a parâmetros tipados: {tipo:nome}
$paramNames = [];
$pattern = preg_replace_callback('/\{([a-zA-Z0-9_]+):([a-zA-Z0-9_.-]+)\}/', function($m) use (&$paramNames) {
$type = strtolower($m[1]);
$original = $m[2];
$safe = preg_replace('/[^a-zA-Z0-9_]/', '_', $original);
$paramNames[$original] = $safe;
switch ($type) {
case 'int': return '___PARAM_INT___' . $safe . '___';
case 'alphanum': return '___PARAM_ALPHANUM___' . $safe . '___';
case 'slug': return '___PARAM_SLUG___' . $safe . '___';
default: return '___PARAM_ANY___' . $safe . '___';
}
}, $pattern);
// Parâmetros não tipados: {nome}
$pattern = preg_replace_callback('/\{([a-zA-Z0-9_.-]+)\}/', function($m) use (&$paramNames) {
$original = $m[1];
$safe = preg_replace('/[^a-zA-Z0-9_]/', '_', $original);
$paramNames[$original] = $safe;
return '___PARAM_ANY___' . $safe . '___';
}, $pattern);
$pattern = preg_quote($pattern, '#');
// Substituir os placeholders por grupos nomeados com regex correto
$pattern = preg_replace('/___PARAM_INT___([a-zA-Z0-9_]+)___/', '(?P<$1>[0-9]+)', $pattern);
$pattern = preg_replace('/___PARAM_ALPHANUM___([a-zA-Z0-9_]+)___/', '(?P<$1>[a-zA-Z0-9]+)', $pattern);
$pattern = preg_replace('/___PARAM_SLUG___([a-zA-Z0-9_]+)___/', '(?P<$1>[a-zA-Z0-9\-]+)', $pattern);
$pattern = preg_replace('/___PARAM_ANY___([a-zA-Z0-9_]+)___/', '(?P<$1>[^/]+)', $pattern);
return '#^' . $pattern . '/?$#';
}
public function dispatch(string $uri, string $method): void
{
if ($method === 'HEAD') {
$method = 'GET';
}
$method = strtoupper($method);
if (!isset($this->routes[$method])) {
$this->handleNotFound();
return;
}
foreach ($this->routes[$method] as $pattern => $routeData) {
$preparedPattern = $this->preparePattern($pattern);
if (preg_match($preparedPattern, $uri, $matches)) {
array_shift($matches);
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
$handler = $routeData['handler'];
$middleware = $routeData['middleware'];
if (!empty($middleware)) {
// This is a simplified middleware handler for the purpose of the example
$authMiddleware = new AuthMiddleware();
if (isset($middleware[0]) && method_exists($authMiddleware, $middleware[1])) {
call_user_func([$authMiddleware, $middleware[1]]);
}
}
if (is_callable($handler)) {
call_user_func_array($handler, $params);
return;
}
if (is_array($handler) && count($handler) === 2) {
[$class, $methodName] = $handler;
if (class_exists($class)) {
$controller = new $class();
if (method_exists($controller, $methodName)) {
// Convert named parameters to positional parameters
$reflection = new \ReflectionMethod($controller, $methodName);
$positionalParams = [];
foreach ($reflection->getParameters() as $i => $param) {
$paramName = $param->getName();
if (isset($params[$paramName])) {
$positionalParams[] = $params[$paramName];
} elseif (isset($params[$i])) {
$positionalParams[] = $params[$i];
} elseif ($param->isDefaultValueAvailable()) {
$positionalParams[] = $param->getDefaultValue();
} else {
$positionalParams[] = null;
}
}
call_user_func_array([$controller, $methodName], $positionalParams);
return;
}
}
}
error_log("Invalid handler for route: " . $pattern);
$this->handleNotFound();
return;
}
}
$this->handleNotFound();
}
private function handleNotFound(): void
{
http_response_code(404);
header('Content-Type: text/plain');
echo '404 Not Found';
// Only log 404 errors that are not expected/common
$uri = $_SERVER['REQUEST_URI'] ?? 'unknown';
// Filter out common/expected 404s to reduce noise
$commonPaths = [
'/favicon.ico',
'/robots.txt',
'/sitemap.xml',
'/apple-touch-icon',
'.well-known',
'/wp-admin',
'/wp-login',
'/admin',
'/phpmyadmin',
'.php.bak',
'.env',
'.git',
'/node_modules',
'/vendor'
];
$shouldLog = true;
foreach ($commonPaths as $path) {
if (strpos($uri, $path) !== false) {
$shouldLog = false;
break;
}
}
// Also filter out requests from bots/crawlers
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$botPatterns = ['bot', 'crawler', 'spider', 'scraper'];
foreach ($botPatterns as $pattern) {
if (stripos($userAgent, $pattern) !== false) {
$shouldLog = false;
break;
}
}
if ($shouldLog) {
$method = $_SERVER['REQUEST_METHOD'] ?? 'unknown';
$referer = $_SERVER['HTTP_REFERER'] ?? 'direct';
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
ErrorReporter::report(new \Exception("404 Not Found"), [
'type' => '404_error',
'uri' => $uri,
'method' => $method,
'user_agent' => $userAgent,
'referer' => $referer,
'ip' => $ip,
'timestamp' => date('Y-m-d H:i:s')
]);
}
}
}
+217
View File
@@ -0,0 +1,217 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Sanitize - Sistema de sanitização de input
* Implementa sanitização defensiva para todos os tipos de input
*/
class Sanitize
{
/**
* Sanitizar string básica
*/
public static function string(?string $value, int $maxLength = 255): string
{
if ($value === null) return '';
$value = trim($value);
$value = strip_tags($value);
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
return substr($value, 0, $maxLength);
}
/**
* Sanitizar email
*/
public static function email(?string $value): string
{
if ($value === null) return '';
$value = trim($value);
$value = filter_var($value, FILTER_SANITIZE_EMAIL);
return $value ?: '';
}
/**
* Sanitizar número inteiro
*/
public static function integer($value, ?int $min = null, ?int $max = null): int
{
$value = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$value = (int)$value;
if ($min !== null && $value < $min) $value = $min;
if ($max !== null && $value > $max) $value = $max;
return $value;
}
/**
* Sanitizar número decimal
*/
public static function decimal($value, int $decimals = 2): float
{
$value = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
return round((float)$value, $decimals);
}
/**
* Sanitizar boolean
*/
public static function boolean($value): bool
{
if (is_bool($value)) {
return $value;
}
if (is_string($value)) {
$value = strtolower(trim($value));
// TRUE values
$trueValues = [
'1', 'true', 'yes', 'y', 'sim', 's', 'ok', 'on', 'active', 'enabled', 'enable',
'verdadeiro', 'v', 'positivo', 'checked'
];
return in_array($value, $trueValues, true);
}
if (is_numeric($value)) {
return $value > 0;
}
return false;
}
/**
* Sanitizar URL
*/
public static function url(?string $value): string
{
if ($value === null) return '';
$value = trim($value);
$value = filter_var($value, FILTER_SANITIZE_URL);
return $value ?: '';
}
/**
* Sanitizar telefone
*/
public static function phone(?string $value): string
{
if ($value === null) return '';
$value = trim($value);
$value = preg_replace('/[^0-9+\-\(\)\s]/', '', $value);
return substr($value, 0, 20);
}
/**
* Sanitizar data
*/
public static function date(?string $value): string
{
if ($value === null || empty(trim($value))) {
return date('Y-m-d');
}
$value = trim($value);
// Validar formato Y-m-d
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
// Verificar se a data é válida
if (checkdate((int)substr($value, 5, 2), (int)substr($value, 8, 2), (int)substr($value, 0, 4))) {
return $value;
}
}
// Tentar converter outros formatos
$timestamp = strtotime($value);
if ($timestamp !== false && $timestamp > 0) {
$formatted = date('Y-m-d', $timestamp);
// Verificar se a data resultante é válida
if ($formatted !== '1970-01-01') {
return $formatted;
}
}
// Se tudo falhar, retornar data atual
return date('Y-m-d');
}
/**
* Sanitizar array
*/
public static function array(array $data, ?callable $sanitizer = null): array
{
if ($sanitizer === null) {
$sanitizer = [self::class, 'string'];
}
return array_map($sanitizer, $data);
}
/**
* Sanitizar para SQL (escapar)
*/
public static function sql(string $value): string
{
return addslashes($value);
}
/**
* Sanitizar para HTML (escapar)
*/
public static function html(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
/**
* Sanitizar para JavaScript (escapar)
*/
public static function js(string $value): string
{
return json_encode($value, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
}
/**
* Sanitizar para atributos HTML
*/
public static function attribute(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
/**
* Sanitizar para CSS
*/
public static function css(string $value): string
{
return preg_replace('/[^a-zA-Z0-9\s\-_\.#]/', '', $value);
}
/**
* Sanitizar nome de ficheiro
*/
public static function filename(string $value): string
{
$value = preg_replace('/[^a-zA-Z0-9\-_\.]/', '', $value);
return substr($value, 0, 255);
}
/**
* Sanitizar slug/URL amigável
*/
public static function slug(string $value): string
{
$value = strtolower($value);
$value = preg_replace('/[^a-z0-9\-]/', '-', $value);
$value = preg_replace('/-+/', '-', $value);
$value = trim($value, '-');
return substr($value, 0, 100);
}
}
+159
View File
@@ -0,0 +1,159 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Service Container para Dependency Injection
* Permite isolamento de módulos e injeção de dependências
*/
class ServiceContainer
{
private static ?ServiceContainer $instance = null;
private array $services = [];
private array $singletons = [];
private array $moduleServices = [];
private function __construct() {}
public static function getInstance(): ServiceContainer
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Registar um serviço
*/
public function register(string $name, callable $factory, bool $singleton = false): void
{
$this->services[$name] = [
'factory' => $factory,
'singleton' => $singleton
];
}
/**
* Registar um serviço específico de um módulo
*/
public function registerModuleService(string $module, string $name, callable $factory, bool $singleton = false): void
{
$this->moduleServices[$module][$name] = [
'factory' => $factory,
'singleton' => $singleton
];
}
/**
* Resolver um serviço
*/
public function resolve(string $name)
{
// Verificar se é singleton já instanciado
if (isset($this->singletons[$name])) {
return $this->singletons[$name];
}
// Verificar serviços globais
if (isset($this->services[$name])) {
$service = $this->services[$name];
$instance = $service['factory']();
if ($service['singleton']) {
$this->singletons[$name] = $instance;
}
return $instance;
}
// Verificar se é um serviço de módulo no formato "Module:ServiceName"
if (strpos($name, ':') !== false) {
[$module, $serviceName] = explode(':', $name, 2);
if (isset($this->moduleServices[$module][$serviceName])) {
$service = $this->moduleServices[$module][$serviceName];
$instance = $service['factory']();
if ($service['singleton']) {
$this->singletons[$name] = $instance;
}
return $instance;
}
}
// Verificar serviços de módulos (formato antigo)
foreach ($this->moduleServices as $module => $services) {
if (isset($services[$name])) {
$service = $services[$name];
$instance = $service['factory']();
if ($service['singleton']) {
$this->singletons[$name] = $instance;
}
return $instance;
}
}
throw new \InvalidArgumentException("Service '$name' not found");
}
/**
* Verificar se um serviço existe
*/
public function has(string $name): bool
{
if (isset($this->services[$name])) {
return true;
}
// Verificar se é um serviço de módulo no formato "Module:ServiceName"
if (strpos($name, ':') !== false) {
[$module, $serviceName] = explode(':', $name, 2);
if (isset($this->moduleServices[$module][$serviceName])) {
return true;
}
}
// Verificar serviços de módulos (formato antigo)
foreach ($this->moduleServices as $services) {
if (isset($services[$name])) {
return true;
}
}
return false;
}
/**
* Limpar todos os serviços (útil para testes)
*/
public function clear(): void
{
$this->services = [];
$this->singletons = [];
$this->moduleServices = [];
}
/**
* Obter lista de serviços registados
*/
public function getRegisteredServices(): array
{
$services = [];
foreach ($this->services as $name => $service) {
$services[] = $name;
}
foreach ($this->moduleServices as $module => $moduleServices) {
foreach ($moduleServices as $name => $service) {
$services[] = "$module:$name";
}
}
return $services;
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace App\Core;
class SessionManager
{
private static ?SessionManager $instance = null;
private bool $started = false;
private function __construct()
{
// Private constructor for singleton
}
public static function getInstance(): SessionManager
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function start(): void
{
if (!$this->started && session_status() === PHP_SESSION_NONE) {
session_start();
$this->started = true;
}
}
public function set(string $key, mixed $value): void
{
$_SESSION[$key] = $value;
}
public function get(string $key, mixed $default = null): mixed
{
return $_SESSION[$key] ?? $default;
}
public function has(string $key): bool
{
return isset($_SESSION[$key]);
}
public function remove(string $key): void
{
unset($_SESSION[$key]);
}
public function destroy(): void
{
if ($this->started) {
session_destroy();
$this->started = false;
}
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Core\System;
class CrontabReader
{
/**
* Lê o crontab do sistema e devolve um array de CrontabTask.
*/
public static function read(): array
{
$output = [];
exec('crontab -l 2>/dev/null', $output);
$tasks = [];
$pendingComments = [];
foreach ($output as $line) {
$trim = trim($line);
if ($trim === '') continue;
if (strpos($trim, '#') === 0) {
$pendingComments[] = ltrim($trim, '# ');
continue;
}
// Ignora env vars (ex: MAILTO=)
if (preg_match('/^[A-Z0-9_]+=/', $trim)) continue;
$task = new CrontabTask($trim, $pendingComments);
$tasks[] = $task;
$pendingComments = [];
}
return $tasks;
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace App\Core\System;
class CrontabTask
{
public string $id;
public string $schedule;
public string $command;
public ?string $args = null;
public ?string $redirect = null;
public ?string $raw = null;
public array $comments = [];
public ?string $special = null; // @reboot, @hourly, etc.
public function __construct(string $rawLine, array $comments = [])
{
$this->raw = $rawLine;
$this->comments = $comments;
$this->parse($rawLine);
$this->id = md5(trim($rawLine));
}
private function parse(string $line): void
{
// Remove inline comments (mas guarda para display)
$line = preg_replace('/\s+#.*/', '', $line);
// Suporte a @reboot, @hourly, etc.
if (preg_match('/^(@\w+)\s+(.*)$/', $line, $matches)) {
$this->special = $matches[1];
$this->schedule = $matches[1];
$rest = $matches[2];
} else {
// Split schedule (5 campos) + comando
$parts = preg_split('/\s+/', $line, 6);
if (count($parts) < 6) {
$this->schedule = '';
$this->command = '';
return;
}
[$min, $hour, $dom, $mon, $dow, $rest] = $parts;
$this->schedule = "$min $hour $dom $mon $dow";
}
// Separa comando, args e redirecionamentos
if (preg_match('/^([^\s]+)(.*?)(\s+>\s*.+)?$/', $rest, $matches)) {
$this->command = trim($matches[1]);
$this->args = isset($matches[2]) ? trim($matches[2]) : null;
$this->redirect = isset($matches[3]) ? trim($matches[3]) : null;
} else {
$this->command = trim($rest);
}
}
public function toArray(): array
{
return [
'id' => $this->id,
'schedule' => $this->schedule,
'command' => $this->command,
'args' => $this->args,
'redirect' => $this->redirect,
'raw' => $this->raw,
'comments' => $this->comments,
'special' => $this->special,
];
}
}
+311
View File
@@ -0,0 +1,311 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Validate - Sistema de validação de input
* Implementa validação defensiva para todos os tipos de input
*/
class Validate
{
/**
* Validar se não está vazio
*/
public static function required($value): bool
{
if (is_string($value)) {
return trim($value) !== '';
}
if (is_array($value)) {
return !empty($value);
}
return $value !== null && $value !== '';
}
/**
* Validar email
*/
public static function email(string $value): bool
{
return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
}
/**
* Validar número inteiro
*/
public static function integer($value, ?int $min = null, ?int $max = null): bool
{
if (!is_numeric($value)) return false;
$value = (int)$value;
if ($min !== null && $value < $min) return false;
if ($max !== null && $value > $max) return false;
return true;
}
/**
* Validar número decimal
*/
public static function decimal($value, ?float $min = null, ?float $max = null): bool
{
if (!is_numeric($value)) return false;
$value = (float)$value;
if ($min !== null && $value < $min) return false;
if ($max !== null && $value > $max) return false;
return true;
}
/**
* Validar URL
*/
public static function url(string $value): bool
{
return filter_var($value, FILTER_VALIDATE_URL) !== false;
}
/**
* Validar telefone
*/
public static function phone(string $value): bool
{
$value = preg_replace('/[^0-9+\-\(\)\s]/', '', $value);
return strlen($value) >= 8 && strlen($value) <= 20;
}
/**
* Validar data
*/
public static function date(string $value, string $format = 'Y-m-d'): bool
{
$date = \DateTime::createFromFormat($format, $value);
return $date && $date->format($format) === $value;
}
/**
* Validar comprimento mínimo
*/
public static function minLength(string $value, int $min): bool
{
return strlen($value) >= $min;
}
/**
* Validar comprimento máximo
*/
public static function maxLength(string $value, int $max): bool
{
return strlen($value) <= $max;
}
/**
* Validar comprimento exato
*/
public static function exactLength(string $value, int $length): bool
{
return strlen($value) === $length;
}
/**
* Validar regex pattern
*/
public static function pattern(string $value, string $pattern): bool
{
return preg_match($pattern, $value) === 1;
}
/**
* Validar se é alfanumérico
*/
public static function alphanumeric(string $value): bool
{
return preg_match('/^[a-zA-Z0-9]+$/', $value) === 1;
}
/**
* Validar se é alfabético
*/
public static function alpha(string $value): bool
{
return preg_match('/^[a-zA-Z\s]+$/', $value) === 1;
}
/**
* Validar se é numérico
*/
public static function numeric(string $value): bool
{
return is_numeric($value);
}
/**
* Validar se é um ficheiro válido
*/
public static function file(array $file): bool
{
return isset($file['tmp_name']) &&
is_uploaded_file($file['tmp_name']) &&
$file['error'] === UPLOAD_ERR_OK;
}
/**
* Validar tipo de ficheiro
*/
public static function fileType(array $file, array $allowedTypes): bool
{
if (!self::file($file)) return false;
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
return in_array($mimeType, $allowedTypes);
}
/**
* Validar tamanho de ficheiro
*/
public static function fileSize(array $file, int $maxSize): bool
{
if (!self::file($file)) return false;
return $file['size'] <= $maxSize;
}
/**
* Validar se valor está em lista
*/
public static function in($value, array $allowedValues): bool
{
return in_array($value, $allowedValues, true);
}
/**
* Validar se valor não está em lista
*/
public static function notIn($value, array $forbiddenValues): bool
{
return !in_array($value, $forbiddenValues, true);
}
/**
* Validar se é um array
*/
public static function array($value): bool
{
return is_array($value);
}
/**
* Validar se é um boolean
*/
public static function boolean($value): bool
{
return is_bool($value) || in_array($value, [0, 1, '0', '1', true, false], true);
}
/**
* Validar se é um JSON válido
*/
public static function json(string $value): bool
{
json_decode($value);
return json_last_error() === JSON_ERROR_NONE;
}
/**
* Validar se é um IP válido
*/
public static function ip(string $value): bool
{
return filter_var($value, FILTER_VALIDATE_IP) !== false;
}
/**
* Validar se é um IPv4 válido
*/
public static function ipv4(string $value): bool
{
return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
}
/**
* Validar se é um IPv6 válido
*/
public static function ipv6(string $value): bool
{
return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
}
/**
* Validar se é um MAC address válido
*/
public static function mac(string $value): bool
{
return filter_var($value, FILTER_VALIDATE_MAC) !== false;
}
/**
* Validar se é um slug válido
*/
public static function slug(string $value): bool
{
return preg_match('/^[a-z0-9\-]+$/', $value) === 1;
}
/**
* Validar se é um username válido
*/
public static function username(string $value): bool
{
return preg_match('/^[a-zA-Z0-9_]{3,20}$/', $value) === 1;
}
/**
* Validar se é uma password forte
*/
public static function strongPassword(string $value): bool
{
// Mínimo 8 caracteres, pelo menos 1 maiúscula, 1 minúscula, 1 número
return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/', $value) === 1;
}
/**
* Validar múltiplas regras
*/
public static function rules($value, array $rules): array
{
$errors = [];
foreach ($rules as $rule) {
$ruleName = $rule;
$ruleParams = [];
if (is_array($rule)) {
$ruleName = $rule[0];
$ruleParams = array_slice($rule, 1);
}
$method = $ruleName;
if (!method_exists(self::class, $method)) {
$errors[] = "Regra de validação '{$ruleName}' não existe";
continue;
}
$result = call_user_func_array([self::class, $method], array_merge([$value], $ruleParams));
if (!$result) {
$errors[] = "Falha na validação: {$ruleName}";
}
}
return $errors;
}
}
+505
View File
@@ -0,0 +1,505 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* Validator - Sistema de validação centralizado e automático
*
* Implementa validação automática baseada em regras definidas,
* eliminando duplicação de código e garantindo consistência.
*/
class Validator
{
private array $data;
private array $rules;
private array $errors = [];
private array $customMessages = [];
private bool $stopOnFirstError = false;
/**
* Construtor
*/
public function __construct(array $data = [], array $rules = [])
{
$this->data = $data;
$this->rules = $rules;
}
/**
* Definir dados para validação
*/
public function setData(array $data): self
{
$this->data = $data;
return $this;
}
/**
* Definir regras de validação
*/
public function setRules(array $rules): self
{
$this->rules = $rules;
return $this;
}
/**
* Definir mensagens customizadas
*/
public function setMessages(array $messages): self
{
$this->customMessages = $messages;
return $this;
}
/**
* Parar na primeira validação que falhar
*/
public function stopOnFirstError(bool $stop = true): self
{
$this->stopOnFirstError = $stop;
return $this;
}
/**
* Validar dados
*/
public function validate(): bool
{
$this->errors = [];
foreach ($this->rules as $field => $fieldRules) {
$value = $this->getFieldValue($field);
$fieldRules = $this->parseRules($fieldRules);
foreach ($fieldRules as $rule) {
$ruleName = $rule['name'];
$ruleParams = $rule['params'];
if (!$this->applyRule($ruleName, $value, $ruleParams, $field)) {
$this->addError($field, $ruleName, $ruleParams);
if ($this->stopOnFirstError) {
return false;
}
}
}
}
return empty($this->errors);
}
/**
* Obter erros de validação
*/
public function getErrors(): array
{
return $this->errors;
}
/**
* Obter primeiro erro
*/
public function getFirstError(): ?string
{
if (empty($this->errors)) {
return null;
}
$firstField = array_key_first($this->errors);
return $this->errors[$firstField][0] ?? null;
}
/**
* Verificar se campo tem erro
*/
public function hasError(string $field): bool
{
return isset($this->errors[$field]);
}
/**
* Obter erros de um campo específico
*/
public function getFieldErrors(string $field): array
{
return $this->errors[$field] ?? [];
}
/**
* Limpar erros
*/
public function clearErrors(): self
{
$this->errors = [];
return $this;
}
/**
* Obter valor do campo
*/
private function getFieldValue(string $field)
{
$keys = explode('.', $field);
$value = $this->data;
foreach ($keys as $key) {
if (!isset($value[$key])) {
return null;
}
$value = $value[$key];
}
return $value;
}
/**
* Parse das regras de validação
*/
private function parseRules(string $rules): array
{
$parsedRules = [];
$ruleList = explode('|', $rules);
foreach ($ruleList as $rule) {
$rule = trim($rule);
if (strpos($rule, ':') !== false) {
[$ruleName, $params] = explode(':', $rule, 2);
$ruleParams = explode(',', $params);
} else {
$ruleName = $rule;
$ruleParams = [];
}
$parsedRules[] = [
'name' => trim($ruleName),
'params' => array_map('trim', $ruleParams)
];
}
return $parsedRules;
}
/**
* Aplicar regra de validação
*/
private function applyRule(string $ruleName, $value, array $params, string $field): bool
{
$method = 'validate' . ucfirst($ruleName);
if (method_exists($this, $method)) {
return $this->$method($value, $params, $field);
}
// Tentar método estático na classe Validate
if (method_exists(Validate::class, $ruleName)) {
return call_user_func_array([Validate::class, $ruleName], array_merge([$value], $params));
}
// Regra customizada
return $this->validateCustom($ruleName, $value, $params, $field);
}
/**
* Adicionar erro
*/
private function addError(string $field, string $rule, array $params = []): void
{
$message = $this->getErrorMessage($field, $rule, $params);
if (!isset($this->errors[$field])) {
$this->errors[$field] = [];
}
$this->errors[$field][] = $message;
}
/**
* Obter mensagem de erro
*/
private function getErrorMessage(string $field, string $rule, array $params = []): string
{
$fieldKey = $field . '.' . $rule;
// Mensagem customizada específica
if (isset($this->customMessages[$fieldKey])) {
return $this->customMessages[$fieldKey];
}
// Mensagem customizada para o campo
if (isset($this->customMessages[$field])) {
return $this->customMessages[$field];
}
// Mensagem padrão
return $this->getDefaultMessage($field, $rule, $params);
}
/**
* Obter mensagem padrão
*/
private function getDefaultMessage(string $field, string $rule, array $params = []): string
{
$fieldName = str_replace('_', ' ', $field);
$fieldName = ucfirst($fieldName);
$messages = [
'required' => "O campo {$fieldName} é obrigatório.",
'email' => "O campo {$fieldName} deve ser um email válido.",
'min' => "O campo {$fieldName} deve ter pelo menos {$params[0]} caracteres.",
'max' => "O campo {$fieldName} deve ter no máximo {$params[0]} caracteres.",
'numeric' => "O campo {$fieldName} deve ser numérico.",
'integer' => "O campo {$fieldName} deve ser um número inteiro.",
'decimal' => "O campo {$fieldName} deve ser um número decimal.",
'url' => "O campo {$fieldName} deve ser uma URL válida.",
'phone' => "O campo {$fieldName} deve ser um telefone válido.",
'date' => "O campo {$fieldName} deve ser uma data válida.",
'alpha' => "O campo {$fieldName} deve conter apenas letras.",
'alphanumeric' => "O campo {$fieldName} deve conter apenas letras e números.",
'in' => "O campo {$fieldName} deve ser um dos valores: " . implode(', ', $params),
'not_in' => "O campo {$fieldName} não pode ser um dos valores: " . implode(', ', $params),
'unique' => "O valor do campo {$fieldName} já existe.",
'exists' => "O valor do campo {$fieldName} não existe.",
'confirmed' => "A confirmação do campo {$fieldName} não coincide.",
'different' => "O campo {$fieldName} deve ser diferente de {$params[0]}.",
'same' => "O campo {$fieldName} deve ser igual a {$params[0]}.",
'regex' => "O formato do campo {$fieldName} é inválido.",
'file' => "O campo {$fieldName} deve ser um arquivo válido.",
'image' => "O campo {$fieldName} deve ser uma imagem válida.",
'mimes' => "O campo {$fieldName} deve ser um arquivo do tipo: " . implode(', ', $params),
'size' => "O campo {$fieldName} deve ter no máximo {$params[0]} KB.",
'between' => "O campo {$fieldName} deve estar entre {$params[0]} e {$params[1]}.",
'min_value' => "O campo {$fieldName} deve ser pelo menos {$params[0]}.",
'max_value' => "O campo {$fieldName} deve ser no máximo {$params[0]}.",
'strong_password' => "O campo {$fieldName} deve ter pelo menos 8 caracteres, incluindo maiúscula, minúscula e número."
];
return $messages[$rule] ?? "O campo {$fieldName} é inválido.";
}
// =============================================================================
// REGRAS DE VALIDAÇÃO ESPECÍFICAS
// =============================================================================
/**
* Validar campo obrigatório
*/
private function validateRequired($value, array $params, string $field): bool
{
return Validate::required($value);
}
/**
* Validar comprimento mínimo
*/
private function validateMin($value, array $params, string $field): bool
{
if (empty($params[0])) return true;
return Validate::minLength($value, (int)$params[0]);
}
/**
* Validar comprimento máximo
*/
private function validateMax($value, array $params, string $field): bool
{
if (empty($params[0])) return true;
return Validate::maxLength($value, (int)$params[0]);
}
/**
* Validar valor mínimo
*/
private function validateMinValue($value, array $params, string $field): bool
{
if (empty($params[0])) return true;
return Validate::decimal($value, (float)$params[0]);
}
/**
* Validar valor máximo
*/
private function validateMaxValue($value, array $params, string $field): bool
{
if (empty($params[0])) return true;
return Validate::decimal($value, null, (float)$params[0]);
}
/**
* Validar entre valores
*/
private function validateBetween($value, array $params, string $field): bool
{
if (count($params) < 2) return true;
return Validate::decimal($value, (float)$params[0], (float)$params[1]);
}
/**
* Validar valores permitidos
*/
private function validateIn($value, array $params, string $field): bool
{
return Validate::in($value, $params);
}
/**
* Validar valores não permitidos
*/
private function validateNotIn($value, array $params, string $field): bool
{
return Validate::notIn($value, $params);
}
/**
* Validar confirmação
*/
private function validateConfirmed($value, array $params, string $field): bool
{
$confirmationField = $field . '_confirmation';
$confirmationValue = $this->getFieldValue($confirmationField);
return $value === $confirmationValue;
}
/**
* Validar diferente de
*/
private function validateDifferent($value, array $params, string $field): bool
{
if (empty($params[0])) return true;
$otherValue = $this->getFieldValue($params[0]);
return $value !== $otherValue;
}
/**
* Validar igual a
*/
private function validateSame($value, array $params, string $field): bool
{
if (empty($params[0])) return true;
$otherValue = $this->getFieldValue($params[0]);
return $value === $otherValue;
}
/**
* Validar regex
*/
private function validateRegex($value, array $params, string $field): bool
{
if (empty($params[0])) return true;
return Validate::pattern($value, $params[0]);
}
/**
* Validar arquivo
*/
private function validateFile($value, array $params, string $field): bool
{
if (!is_array($value)) return false;
return Validate::file($value);
}
/**
* Validar imagem
*/
private function validateImage($value, array $params, string $field): bool
{
if (!is_array($value)) return false;
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
return Validate::fileType($value, $allowedTypes);
}
/**
* Validar tipos MIME
*/
private function validateMimes($value, array $params, string $field): bool
{
if (!is_array($value)) return false;
return Validate::fileType($value, $params);
}
/**
* Validar tamanho do arquivo
*/
private function validateSize($value, array $params, string $field): bool
{
if (!is_array($value)) return false;
if (empty($params[0])) return true;
$maxSize = (int)$params[0] * 1024; // Converter KB para bytes
return Validate::fileSize($value, $maxSize);
}
/**
* Validar password forte
*/
private function validateStrongPassword($value, array $params, string $field): bool
{
return Validate::strongPassword($value);
}
/**
* Validar regra customizada
*/
private function validateCustom(string $ruleName, $value, array $params, string $field): bool
{
// Permitir extensão com regras customizadas
$customMethod = 'validate' . ucfirst($ruleName);
if (method_exists($this, $customMethod)) {
return $this->$customMethod($value, $params, $field);
}
// Por padrão, aceitar se não encontrar regra
return true;
}
// =============================================================================
// MÉTODOS ESTÁTICOS PARA FACILITAR USO
// =============================================================================
/**
* Validação rápida
*/
public static function make(array $data, array $rules, array $messages = []): self
{
$validator = new self($data, $rules);
if (!empty($messages)) {
$validator->setMessages($messages);
}
return $validator;
}
/**
* Validação com resposta JSON
*/
public static function validateJson(array $data, array $rules, array $messages = []): array
{
$validator = self::make($data, $rules, $messages);
$isValid = $validator->validate();
return [
'valid' => $isValid,
'errors' => $validator->getErrors(),
'first_error' => $validator->getFirstError()
];
}
/**
* Validar e lançar exceção se falhar
*/
public static function validateOrFail(array $data, array $rules, array $messages = []): array
{
$validator = self::make($data, $rules, $messages);
if (!$validator->validate()) {
throw new \InvalidArgumentException(
'Validation failed: ' . $validator->getFirstError()
);
}
return $data;
}
}
+536
View File
@@ -0,0 +1,536 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* ValidatorFactory - Sistema de validação centralizado e automático
* Fornece regras de validação reutilizáveis e validação automática
*/
class ValidatorFactory
{
private static array $rules = [];
private static array $messages = [];
private static array $customValidators = [];
/**
* Inicializar o sistema de validação
*/
public static function initialize(): void
{
self::registerDefaultRules();
self::registerDefaultMessages();
self::registerCustomValidators();
}
/**
* Registar regras padrão do sistema
*/
private static function registerDefaultRules(): void
{
// Regras para utilizadores
self::$rules['user.create'] = [
'first_name' => 'required|min:2|max:50|alpha',
'last_name' => 'required|min:2|max:50|alpha',
'email' => 'required|email|max:100|unique:users,email',
'username' => 'required|min:3|max:20|alphanumeric|unique:users,username',
'password' => 'required|min:8|strong_password',
'password_confirmation' => 'required|confirmed',
'role' => 'required|in:admin,user,manager'
];
self::$rules['user.update'] = [
'first_name' => 'required|min:2|max:50|alpha',
'last_name' => 'required|min:2|max:50|alpha',
'email' => 'required|email|max:100',
'phone' => 'nullable|phone|max:20',
'city' => 'nullable|max:100',
'country' => 'nullable|max:100',
'zipcode' => 'nullable|max:20',
'website' => 'nullable|url|max:255',
'job_title' => 'nullable|max:100',
'company_name' => 'nullable|max:100',
'description' => 'nullable|max:500'
];
// Regras para contactos
self::$rules['contact.create'] = [
'first_name' => 'required|min:2|max:50|alpha',
'last_name' => 'required|min:2|max:50|alpha',
'email' => 'required|email|max:100',
'phone' => 'nullable|phone|max:20',
'mobile' => 'nullable|phone|max:20',
'job_title' => 'nullable|max:100',
'company_id' => 'nullable|integer|exists:companies,id',
'website' => 'nullable|url|max:255',
'address' => 'nullable|max:255',
'city' => 'nullable|max:100',
'state' => 'nullable|max:100',
'country' => 'nullable|max:100',
'zip_code' => 'nullable|max:20',
'notes' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,lead,customer,prospect',
'source' => 'nullable|max:100',
'created_by' => 'nullable|integer|exists:users,id'
];
self::$rules['contact.update'] = [
'first_name' => 'required|min:2|max:50|alpha',
'last_name' => 'required|min:2|max:50|alpha',
'email' => 'required|email|max:100',
'phone' => 'nullable|phone|max:20',
'mobile' => 'nullable|phone|max:20',
'job_title' => 'nullable|max:100',
'company_id' => 'nullable|integer|exists:companies,id',
'website' => 'nullable|url|max:255',
'address' => 'nullable|max:255',
'city' => 'nullable|max:100',
'state' => 'nullable|max:100',
'country' => 'nullable|max:100',
'zip_code' => 'nullable|max:20',
'notes' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,lead,customer,prospect',
'source' => 'nullable|max:100',
'updated_by' => 'nullable|integer|exists:users,id'
];
// Regras para empresas
self::$rules['company.create'] = [
'name' => 'required|min:2|max:255',
'email' => 'nullable|email|max:100',
'phone' => 'nullable|phone|max:20',
'website' => 'nullable|url|max:255',
'address' => 'nullable|max:255',
'city' => 'nullable|max:100',
'state' => 'nullable|max:100',
'country' => 'nullable|max:100',
'zip_code' => 'nullable|max:20',
'industry' => 'nullable|max:100',
'company_size' => 'nullable|in:1-10,11-50,51-200,201-500,501-1000,1000+',
'annual_revenue' => 'nullable|decimal|min_value:0',
'description' => 'nullable|max:1000',
'notes' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,prospect,customer,partner',
'source' => 'nullable|max:100'
];
self::$rules['company.update'] = [
'name' => 'required|min:2|max:255',
'email' => 'nullable|email|max:100',
'phone' => 'nullable|phone|max:20',
'website' => 'nullable|url|max:255',
'address' => 'nullable|max:255',
'city' => 'nullable|max:100',
'state' => 'nullable|max:100',
'country' => 'nullable|max:100',
'zip_code' => 'nullable|max:20',
'industry' => 'nullable|max:100',
'company_size' => 'nullable|in:1-10,11-50,51-200,201-500,501-1000,1000+',
'annual_revenue' => 'nullable|decimal|min_value:0',
'description' => 'nullable|max:1000',
'notes' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,prospect,customer,partner',
'source' => 'nullable|max:100'
];
// Regras para negócios
self::$rules['deal.create'] = [
'title' => 'required|min:3|max:255',
'description' => 'nullable|max:1000',
'value' => 'nullable|decimal|min_value:0',
'stage' => 'required|in:new,qualification,proposal,negotiation,closed_won,closed_lost',
'status' => 'required|in:open,closed',
'company_id' => 'nullable|integer|exists:companies,id',
'contact_id' => 'nullable|integer|exists:contacts,id',
'expected_close_date' => 'nullable|date|after:today',
'probability' => 'nullable|integer|between:0,100',
'source' => 'nullable|max:100',
'notes' => 'nullable|max:1000'
];
self::$rules['deal.update'] = [
'title' => 'required|min:3|max:255',
'description' => 'nullable|max:1000',
'value' => 'nullable|decimal|min_value:0',
'stage' => 'required|in:new,qualification,proposal,negotiation,closed_won,closed_lost',
'status' => 'required|in:open,closed',
'company_id' => 'nullable|integer|exists:companies,id',
'contact_id' => 'nullable|integer|exists:contacts,id',
'expected_close_date' => 'nullable|date',
'probability' => 'nullable|integer|between:0,100',
'source' => 'nullable|max:100',
'notes' => 'nullable|max:1000'
];
// Regras para leads
self::$rules['lead.create'] = [
'name' => 'required|min:2|max:255',
'email' => 'required|email|max:100',
'phone' => 'nullable|phone|max:20',
'company' => 'nullable|max:255',
'job_title' => 'nullable|max:100',
'source' => 'nullable|max:100',
'status' => 'required|in:new,contacted,qualified,converted,lost',
'score' => 'nullable|integer|between:1,10',
'notes' => 'nullable|max:1000',
'assigned_to' => 'nullable|integer|exists:users,id',
'created_by' => 'nullable|integer|exists:users,id'
];
self::$rules['lead.update'] = [
'name' => 'required|min:2|max:255',
'email' => 'required|email|max:100',
'phone' => 'nullable|phone|max:20',
'company' => 'nullable|max:255',
'job_title' => 'nullable|max:100',
'source' => 'nullable|max:100',
'status' => 'required|in:new,contacted,qualified,converted,lost',
'score' => 'nullable|integer|between:1,10',
'notes' => 'nullable|max:1000',
'assigned_to' => 'nullable|integer|exists:users,id',
'updated_by' => 'nullable|integer|exists:users,id'
];
// Regras para tarefas
self::$rules['task.create'] = [
'title' => 'required|min:3|max:255',
'description' => 'nullable|max:1000',
'due_date' => 'required|date|after:today',
'priority' => 'required|in:low,medium,high,urgent',
'status' => 'required|in:pending,in_progress,completed,cancelled',
'assigned_to' => 'nullable|integer|exists:users,id',
'related_type' => 'nullable|in:contact,company,deal,lead',
'related_id' => 'nullable|integer',
'notes' => 'nullable|max:1000'
];
self::$rules['task.update'] = [
'title' => 'required|min:3|max:255',
'description' => 'nullable|max:1000',
'due_date' => 'required|date',
'priority' => 'required|in:low,medium,high,urgent',
'status' => 'required|in:pending,in_progress,completed,cancelled',
'assigned_to' => 'nullable|integer|exists:users,id',
'related_type' => 'nullable|in:contact,company,deal,lead',
'related_id' => 'nullable|integer',
'notes' => 'nullable|max:1000'
];
// Regras para campanhas
self::$rules['campaign.create'] = [
'name' => 'required|min:3|max:255',
'alias' => 'nullable|max:255',
'seller_id' => 'nullable|integer',
'category' => 'nullable|max:100',
'observations' => 'nullable|max:1000',
'description' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,draft,paused',
'budget' => 'nullable|decimal|min_value:0',
'budget_type' => 'nullable|max:50',
'start_date' => 'nullable|date',
'end_date' => 'nullable|date|after:start_date',
'has_end_date' => 'nullable|boolean',
'expire_hours' => 'nullable|integer|min_value:0',
'expire_mobile_hours' => 'nullable|integer|min_value:0',
'wait_seconds' => 'nullable|integer|min_value:0',
'trigger_timer_seconds' => 'nullable|integer|min_value:0',
'iframe_url' => 'nullable|url|max:500',
'timezone' => 'nullable|max:50',
'targeting_rules' => 'nullable|max:2000',
'disabled_countries' => 'nullable|max:1000',
'allowed_countries' => 'nullable|max:1000',
'allowed_formats' => 'nullable|max:500',
'allow_subdomains' => 'nullable|boolean',
'hide_referer' => 'nullable|boolean',
'disable_mobile' => 'nullable|boolean',
'disable_desktop' => 'nullable|boolean',
'theme' => 'nullable|max:100',
'pricing_info' => 'nullable|max:500',
'garbage_tracker_url' => 'nullable|url|max:500',
'frequency_cap' => 'nullable|integer|min_value:0',
'frequency_period' => 'nullable|integer|min_value:0',
'region' => 'nullable|max:100'
];
self::$rules['campaign.update'] = [
'name' => 'nullable|min:3|max:255',
'alias' => 'nullable|max:255',
'seller_id' => 'nullable|integer',
'category' => 'nullable|max:100',
'observations' => 'nullable|max:1000',
'description' => 'nullable|max:1000',
'status' => 'nullable|in:active,inactive,draft,paused',
'budget' => 'nullable|decimal|min_value:0',
'budget_type' => 'nullable|max:50',
'start_date' => 'nullable|date',
'end_date' => 'nullable|date|after:start_date',
'has_end_date' => 'nullable|boolean',
'expire_hours' => 'nullable|integer|min_value:0',
'expire_mobile_hours' => 'nullable|integer|min_value:0',
'wait_seconds' => 'nullable|integer|min_value:0',
'trigger_timer_seconds' => 'nullable|integer|min_value:0',
'iframe_url' => 'nullable|url|max:500',
'timezone' => 'nullable|max:50',
'targeting_rules' => 'nullable|max:2000',
'disabled_countries' => 'nullable|max:1000',
'allowed_countries' => 'nullable|max:1000',
'allowed_formats' => 'nullable|max:500',
'allow_subdomains' => 'nullable|boolean',
'hide_referer' => 'nullable|boolean',
'disable_mobile' => 'nullable|boolean',
'disable_desktop' => 'nullable|boolean',
'theme' => 'nullable|max:100',
'pricing_info' => 'nullable|max:500',
'garbage_tracker_url' => 'nullable|url|max:500',
'frequency_cap' => 'nullable|integer|min_value:0',
'frequency_period' => 'nullable|integer|min_value:0',
'region' => 'nullable|max:100'
];
// Regras para projetos
self::$rules['project.create'] = [
'name' => 'required|min:3|max:255',
'description' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,completed,on_hold,cancelled',
'priority' => 'required|in:low,medium,high,urgent',
'start_date' => 'required|date',
'end_date' => 'nullable|date|after:start_date',
'budget' => 'nullable|decimal|min_value:0',
'manager_id' => 'nullable|integer|exists:users,id',
'client_id' => 'nullable|integer|exists:clients,id'
];
self::$rules['project.update'] = [
'name' => 'required|min:3|max:255',
'description' => 'nullable|max:1000',
'status' => 'required|in:active,inactive,completed,on_hold,cancelled',
'priority' => 'required|in:low,medium,high,urgent',
'start_date' => 'required|date',
'end_date' => 'nullable|date|after:start_date',
'budget' => 'nullable|decimal|min_value:0',
'manager_id' => 'nullable|integer|exists:users,id',
'client_id' => 'nullable|integer|exists:clients,id'
];
// Regras para autenticação
self::$rules['auth.login'] = [
'email' => 'required|email|max:100',
'password' => 'required|min:1',
'remember_me' => 'nullable|boolean'
];
self::$rules['auth.register'] = [
'first_name' => 'required|min:2|max:50|alpha',
'last_name' => 'required|min:2|max:50|alpha',
'email' => 'required|email|max:100|unique:users,email',
'username' => 'required|min:3|max:20|alphanumeric|unique:users,username',
'password' => 'required|min:8|strong_password',
'password_confirmation' => 'required|confirmed',
'terms' => 'required|accepted'
];
self::$rules['auth.reset_password'] = [
'email' => 'required|email|max:100|exists:users,email',
'token' => 'required|min:10',
'password' => 'required|min:8|strong_password',
'password_confirmation' => 'required|confirmed'
];
// Regras para uploads
self::$rules['file.upload'] = [
'file' => 'required|file|size:5120', // 5MB max
'allowed_types' => 'nullable|in:image,document,video,audio'
];
self::$rules['image.upload'] = [
'image' => 'required|image|size:2048', // 2MB max
'max_width' => 'nullable|integer|min_value:1|max_value:5000',
'max_height' => 'nullable|integer|min_value:1|max_value:5000'
];
}
/**
* Registar mensagens de erro padrão
*/
private static function registerDefaultMessages(): void
{
self::$messages = [
'required' => 'O campo :field é obrigatório.',
'email' => 'O campo :field deve ser um endereço de email válido.',
'min' => 'O campo :field deve ter pelo menos :param caracteres.',
'max' => 'O campo :field não pode ter mais de :param caracteres.',
'alpha' => 'O campo :field deve conter apenas letras.',
'alphanumeric' => 'O campo :field deve conter apenas letras e números.',
'integer' => 'O campo :field deve ser um número inteiro.',
'decimal' => 'O campo :field deve ser um número decimal válido.',
'date' => 'O campo :field deve ser uma data válida.',
'url' => 'O campo :field deve ser um URL válido.',
'phone' => 'O campo :field deve ser um número de telefone válido.',
'in' => 'O valor do campo :field não é válido.',
'between' => 'O campo :field deve estar entre :param1 e :param2.',
'exists' => 'O valor selecionado para :field não existe.',
'unique' => 'O valor do campo :field já está em uso.',
'confirmed' => 'A confirmação do campo :field não corresponde.',
'strong_password' => 'A palavra-passe deve conter pelo menos 8 caracteres, incluindo maiúsculas, minúsculas, números e símbolos.',
'file' => 'O campo :field deve ser um ficheiro válido.',
'image' => 'O campo :field deve ser uma imagem válida.',
'size' => 'O campo :field não pode exceder :param KB.',
'after' => 'O campo :field deve ser uma data posterior a :param.',
'after_or_equal' => 'O campo :field deve ser uma data posterior ou igual a :param.'
];
}
/**
* Registar validadores personalizados
*/
private static function registerCustomValidators(): void
{
self::$customValidators = [
'strong_password' => function($value) {
return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/', $value);
},
'phone' => function($value) {
return preg_match('/^[\+]?[1-9][\d]{0,15}$/', preg_replace('/[^0-9+]/', '', $value));
},
'unique' => function($value, $params) {
[$table, $column] = explode(',', $params);
$db = DatabaseManager::getInstance();
$result = $db->fetch("SELECT COUNT(*) as count FROM $table WHERE $column = ?", [$value]);
return $result['count'] == 0;
},
'exists' => function($value, $params) {
[$table, $column] = explode(',', $params);
$db = DatabaseManager::getInstance();
$result = $db->fetch("SELECT COUNT(*) as count FROM $table WHERE $column = ?", [$value]);
return $result['count'] > 0;
}
];
}
/**
* Obter regras para um tipo específico
*/
public static function getRules(string $type): array
{
if (!isset(self::$rules[$type])) {
throw new \InvalidArgumentException("Validation rules for type '$type' not found");
}
return self::$rules[$type];
}
/**
* Obter mensagens de erro
*/
public static function getMessages(): array
{
return self::$messages;
}
/**
* Obter um validador personalizado
*/
public static function getCustomValidator(string $name): ?callable
{
return self::$customValidators[$name] ?? null;
}
/**
* Registar novas regras
*/
public static function registerRules(string $type, array $rules): void
{
self::$rules[$type] = $rules;
}
/**
* Registar novas mensagens
*/
public static function registerMessages(array $messages): void
{
self::$messages = array_merge(self::$messages, $messages);
}
/**
* Registar um validador personalizado
*/
public static function registerCustomValidator(string $name, callable $validator): void
{
self::$customValidators[$name] = $validator;
}
/**
* Validar dados automaticamente
*/
public static function validate(array $data, string $type): array
{
$rules = self::getRules($type);
$messages = self::getMessages();
$validator = Validator::make($data, $rules, $messages);
if (!$validator->validate()) {
return [
'success' => false,
'errors' => $validator->getErrors(),
'first_error' => $validator->getFirstError()
];
}
return ['success' => true];
}
/**
* Validar e retornar dados sanitizados
*/
public static function validateAndSanitize(array $data, string $type): array
{
$validation = self::validate($data, $type);
if (!$validation['success']) {
return $validation;
}
// Sanitizar dados válidos
$sanitized = [];
foreach ($data as $key => $value) {
if (isset($validation['rules'][$key])) {
$sanitized[$key] = self::sanitizeValue($value, $validation['rules'][$key]);
} else {
$sanitized[$key] = $value;
}
}
return [
'success' => true,
'data' => $sanitized
];
}
/**
* Sanitizar valor baseado no tipo de validação
*/
private static function sanitizeValue($value, string $rule): mixed
{
if (strpos($rule, 'email') !== false) {
return filter_var($value, FILTER_SANITIZE_EMAIL);
}
if (strpos($rule, 'url') !== false) {
return filter_var($value, FILTER_SANITIZE_URL);
}
if (strpos($rule, 'integer') !== false) {
return (int) $value;
}
if (strpos($rule, 'decimal') !== false) {
return (float) $value;
}
if (strpos($rule, 'alpha') !== false || strpos($rule, 'alphanumeric') !== false) {
return trim(strip_tags($value));
}
return trim($value);
}
}
+318
View File
@@ -0,0 +1,318 @@
<?php
declare(strict_types=1);
namespace App\Core;
/**
* View - Sistema de renderização de views com suporte a assets modulares
*/
class View
{
private static array $namespaces = [];
private static array $assets = [];
private static array $loadedModules = [];
/**
* Add a namespace for a views directory.
* @param string $namespace The namespace name (e.g., 'crm').
* @param string $path The path to the module's views directory.
*/
public static function addNamespace(string $namespace, string $path): void
{
self::$namespaces[$namespace] = rtrim($path, '/\\');
}
/**
* Renderizar uma view com suporte a assets modulares
*/
public static function render(string $view, array $data = []): void
{
// Initialize AssetManager if not already done
AssetManager::initialize();
// Auto-detect and load module assets based on view path
self::autoLoadModuleAssets($view);
// Extract data to variables
extract($data);
// Include module assets in head if rendering main layout
if (strpos($view, 'layouts/main.php') !== false) {
$data['module_css'] = self::getModuleCss();
$data['module_js'] = self::getModuleJs();
extract($data);
}
// Render the view
$viewPath = self::getViewPath($view);
if (!file_exists($viewPath)) {
throw new \Exception("View file not found: {$view}");
}
include $viewPath;
}
/**
* Auto-load module assets based on view path
*/
private static function autoLoadModuleAssets(string $view): void
{
$assetManager = AssetManager::getInstance();
// Get active modules from AssetManager
$activeModules = $assetManager->getActiveModules();
// Also detect modules from view path
if (strpos($view, '@') === 0) {
// Module-specific view (@modulename/view)
$parts = explode('/', substr($view, 1));
if (!empty($parts[0])) {
$moduleName = ucfirst($parts[0]);
if (!in_array($moduleName, $activeModules)) {
$activeModules[] = $moduleName;
}
}
}
// Load assets for active modules
foreach ($activeModules as $module) {
if (!in_array($module, self::$loadedModules)) {
self::$loadedModules[] = $module;
}
}
}
/**
* Get CSS links for loaded modules
*/
private static function getModuleCss(): string
{
$assetManager = AssetManager::getInstance();
return $assetManager->getCssLinks(self::$loadedModules);
}
/**
* Get JS scripts for loaded modules
*/
private static function getModuleJs(): string
{
$assetManager = AssetManager::getInstance();
return $assetManager->getJsScripts(self::$loadedModules);
}
/**
* Get view path
*/
private static function getViewPath(string $view): string
{
// Handle module-specific views (@modulename/view)
if (strpos($view, '@') === 0) {
$parts = explode('/', substr($view, 1), 2);
$namespace = $parts[0];
$viewFile = $parts[1] ?? 'index.php';
// Add .php extension if not present
if (substr($viewFile, -4) !== '.php') {
$viewFile .= '.php';
}
// Check if namespace is registered
if (isset(self::$namespaces[$namespace])) {
return self::$namespaces[$namespace] . '/' . $viewFile;
}
// Fallback to module path
return PathManager::getModulesPath() . '/' . ucfirst($namespace) . '/Views/' . $viewFile;
}
// Handle absolute paths (starting with /)
if (strpos($view, '/') === 0) {
// Add .php extension if not present
if (substr($view, -4) !== '.php') {
$view .= '.php';
}
return $view;
}
// Handle relative paths (starting with app/, modules/, etc.)
if (strpos($view, 'app/') === 0 || strpos($view, 'modules/') === 0) {
// Add .php extension if not present
if (substr($view, -4) !== '.php') {
$view .= '.php';
}
return PathManager::getRootPath() . '/' . $view;
}
// Regular views - look in multiple locations
$basePaths = [
PathManager::getAppPath() . '/Views',
PathManager::getRootPath() . '/Views',
PathManager::getRootPath() . '/app/Views'
];
// Add .php extension if not present
if (substr($view, -4) !== '.php') {
$view .= '.php';
}
// Try each base path
foreach ($basePaths as $basePath) {
$fullPath = $basePath . '/' . $view;
if (file_exists($fullPath)) {
return $fullPath;
}
}
// If not found, return the first possible path for error reporting
return $basePaths[0] . '/' . $view;
}
/**
* Register an asset to be loaded (renamed to avoid conflict)
*/
public static function registerAsset(string $asset): void
{
if (!in_array($asset, self::$assets)) {
self::$assets[] = $asset;
}
}
/**
* Get all registered assets
*/
public static function getAssets(): array
{
return self::$assets;
}
/**
* Render a component with its own assets
*/
public static function component(string $component, array $data = []): void
{
// Auto-load component-specific assets
$componentModule = self::getComponentModule($component);
if ($componentModule && !in_array($componentModule, self::$loadedModules)) {
self::$loadedModules[] = $componentModule;
}
self::render($component, $data);
}
/**
* Get module name from component path
*/
private static function getComponentModule(string $component): ?string
{
if (strpos($component, 'components/') === 0) {
$parts = explode('/', $component);
if (count($parts) >= 2) {
return ucfirst($parts[1]);
}
}
return null;
}
/**
* Compile and serve module SCSS assets
*/
public static function compileModuleAssets(): bool
{
$assetManager = AssetManager::getInstance();
return $assetManager->compileScssAssets();
}
/**
* Get debug information about loaded modules and assets
*/
public static function getDebugInfo(): array
{
$assetManager = AssetManager::getInstance();
return [
'loaded_modules' => self::$loadedModules,
'registered_assets' => self::$assets,
'discovered_assets' => $assetManager->getRegisteredAssets(),
'active_modules' => $assetManager->getActiveModules(),
];
}
/**
* Include a view partial. This is a simple include wrapper.
* @param string $path Path to the view file relative to app/Views
* @param array $params Parameters to pass to the view
*/
public static function include(string $path, array $params = []): void
{
$fullPath = self::getViewPath($path);
if (file_exists($fullPath)) {
extract($params);
include $fullPath;
} else {
error_log("Include file not found: " . $fullPath);
}
}
/**
* Get the full URL for an asset.
* @param string $path Asset path relative to public/assets
* @return string Full URL to the asset
*/
public static function asset(string $path): string
{
// Remove leading slash and ensure path starts with assets/
$path = ltrim($path, '/');
if (!str_starts_with($path, 'assets/')) {
$path = 'assets/' . $path;
}
return self::getBaseUrl() . '/' . $path;
}
/**
* Get the base URL for the application.
* @return string Base URL
*/
public static function getBaseUrl(): string
{
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
// If HTTP_HOST already includes the port, use it as is
if (strpos($host, ':') !== false) {
return $protocol . '://' . $host;
}
// Otherwise, add port if needed
$port = $_SERVER['SERVER_PORT'] ?? '';
$port = ($port === '80' || $port === '443') ? '' : ':' . $port;
return $protocol . '://' . $host . $port;
}
/**
* Render a view to a string instead of outputting directly.
* @param string $view View path
* @param array $data Data to pass to the view
* @return string Rendered view content
*/
public static function renderToString(string $view, array $data = []): string
{
ob_start();
self::render($view, $data);
return ob_get_clean();
}
/**
* Reset view state (for testing)
*/
public static function reset(): void
{
self::$namespaces = [];
self::$assets = [];
self::$loadedModules = [];
}
}
@@ -0,0 +1,307 @@
<?php
namespace App\Modules\Redirects\Controllers\Api;
use App\Core\BaseController;
use App\Core\ErrorReporter;
class RedirectsApiController extends BaseController
{
public function __construct()
{
parent::__construct('Redirects');
}
/**
* Get redirect types for forms
*/
public function getRedirectTypes(): void
{
try {
header('Content-Type: application/json');
$types = [
['value' => '302', 'label' => '302 - Temporary Redirect'],
['value' => '301', 'label' => '301 - Permanent Redirect'],
['value' => 'meta', 'label' => 'Meta Refresh'],
['value' => 'javascript', 'label' => 'JavaScript']
];
echo json_encode([
'success' => true,
'data' => $types
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'redirects_api_get_types']);
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
}
}
/**
* Get redirect statuses for forms
*/
public function getStatuses(): void
{
try {
header('Content-Type: application/json');
$statuses = [
['value' => '1', 'label' => 'Active'],
['value' => '0', 'label' => 'Inactive']
];
echo json_encode([
'success' => true,
'data' => $statuses
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'redirects_api_get_statuses']);
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
}
}
/**
* Get filter types for redirects
*/
public function getFilterTypes(): void
{
try {
header('Content-Type: application/json');
$filterTypes = [
['value' => 'country', 'label' => 'Country'],
['value' => 'browser', 'label' => 'Browser'],
['value' => 'device_type', 'label' => 'Device Type'],
['value' => 'os', 'label' => 'Operating System'],
['value' => 'language', 'label' => 'Language'],
['value' => 'hour', 'label' => 'Hour of Day'],
['value' => 'referer', 'label' => 'Referer']
];
echo json_encode([
'success' => true,
'data' => $filterTypes
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'redirects_api_get_filter_types']);
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
}
}
/**
* Get filter operators for redirects
*/
public function getFilterOperators(): void
{
try {
header('Content-Type: application/json');
$operators = [
['value' => 'equals', 'label' => 'Equals'],
['value' => 'contains', 'label' => 'Contains'],
['value' => 'starts_with', 'label' => 'Starts with'],
['value' => 'ends_with', 'label' => 'Ends with'],
['value' => 'in', 'label' => 'In list'],
['value' => 'not_in', 'label' => 'Not in list'],
['value' => 'greater_than', 'label' => 'Greater than'],
['value' => 'less_than', 'label' => 'Less than'],
['value' => 'between', 'label' => 'Between']
];
echo json_encode([
'success' => true,
'data' => $operators
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'redirects_api_get_filter_operators']);
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
}
}
/**
* Get redirect settings
*/
public function getSettings(): void
{
try {
header('Content-Type: application/json');
// Default settings for redirects module
$settings = [
'default_redirect_type' => '302',
'tracking_enabled' => true,
'max_redirects_per_day' => 10000,
'enable_analytics' => true,
'enable_filters' => true,
'cache_redirects' => true,
'cache_duration' => 3600
];
echo json_encode([
'success' => true,
'data' => $settings
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'redirects_api_get_settings']);
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
}
}
/**
* Update redirect settings
*/
public function updateSettings(): void
{
try {
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true) ?: [];
// Here you would normally save settings to database
// For now, just return success
echo json_encode([
'success' => true,
'message' => 'Settings updated successfully',
'data' => $input
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'redirects_api_update_settings']);
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
}
}
/**
* Get redirect statistics
*/
public function statsApi(): void
{
try {
header('Content-Type: application/json');
$startDate = $_GET['start_date'] ?? null;
$endDate = $_GET['end_date'] ?? null;
$trackerId = $_GET['tracker_id'] ?? null;
$country = $_GET['country'] ?? null;
$device = $_GET['device'] ?? null;
$browser = $_GET['browser'] ?? null;
$os = $_GET['os'] ?? null;
// Build WHERE clause for filtering
$whereConditions = [];
$params = [];
if ($startDate && $endDate) {
$whereConditions[] = "DATE(timestamp) BETWEEN ? AND ?";
$params[] = $startDate;
$params[] = $endDate;
} elseif ($startDate) {
$whereConditions[] = "DATE(timestamp) >= ?";
$params[] = $startDate;
} elseif ($endDate) {
$whereConditions[] = "DATE(timestamp) <= ?";
$params[] = $endDate;
}
if ($trackerId) {
$whereConditions[] = "redirect_id = ?";
$params[] = $trackerId;
}
if ($country) {
$whereConditions[] = "country_code = ?";
$params[] = $country;
}
if ($device) {
$whereConditions[] = "device_type = ?";
$params[] = $device;
}
if ($browser) {
$whereConditions[] = "browser = ?";
$params[] = $browser;
}
if ($os) {
$whereConditions[] = "os = ?";
$params[] = $os;
}
$whereClause = empty($whereConditions) ? "" : "WHERE " . implode(" AND ", $whereConditions);
// Get overall stats from database
$sql = "SELECT
COUNT(*) as total_clicks,
COUNT(DISTINCT session_id) as unique_clicks,
COUNT(DISTINCT ip_address) as unique_ips,
AVG(response_time_ms) as avg_response_time
FROM redirect_stats " . $whereClause;
$overviewStats = \App\Core\DatabaseManager::getInstance()->fetch($sql, $params) ?: [
'total_clicks' => 0,
'unique_clicks' => 0,
'unique_ips' => 0,
'avg_response_time' => 0
];
// Get stats by country
$countryWhereConditions = array_merge($whereConditions, ["country_code IS NOT NULL", "country_code != ''"]);
$countryWhereClause = "WHERE " . implode(" AND ", $countryWhereConditions);
$sql = "SELECT
country_code,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
$countryWhereClause
GROUP BY country_code
ORDER BY clicks DESC
LIMIT 10";
$countryStats = \App\Core\DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
// Get stats by device
$deviceWhereConditions = array_merge($whereConditions, ["device_type IS NOT NULL"]);
$deviceWhereClause = empty($deviceWhereConditions) ? "" : "WHERE " . implode(" AND ", $deviceWhereConditions);
$sql = "SELECT
device_type,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
$deviceWhereClause
GROUP BY device_type
ORDER BY clicks DESC";
$deviceStats = \App\Core\DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
// Get stats by browser
$browserWhereConditions = array_merge($whereConditions, ["browser IS NOT NULL"]);
$browserWhereClause = empty($browserWhereConditions) ? "" : "WHERE " . implode(" AND ", $browserWhereConditions);
$sql = "SELECT
browser,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
$browserWhereClause
GROUP BY browser
ORDER BY clicks DESC";
$browserStats = \App\Core\DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
echo json_encode([
'success' => true,
'data' => [
'overview' => $overviewStats,
'by_country' => $countryStats,
'by_device' => $deviceStats,
'by_browser' => $browserStats
]
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'redirects_api_stats']);
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
}
}
}
@@ -0,0 +1,368 @@
<?php
namespace App\Modules\Redirects\Controllers;
use App\Core\BaseController;
use App\Core\View;
use App\Modules\Redirects\Models\RedirectModel;
use App\Modules\Redirects\Models\RedirectStatsModel;
use App\Modules\Redirects\Services\RedirectProcessor;
class PublicRedirectsController extends BaseController
{
private RedirectModel $redirectModel;
public function __construct()
{
parent::__construct();
$this->redirectModel = new RedirectModel();
}
public function dashboard(): void
{
try {
$stats = [
'total_redirects' => $this->redirectModel->getCount(),
'active_redirects' => $this->redirectModel->getActiveCount(),
'total_clicks' => 0, // Analytics handled by Advertising module
'unique_clicks' => 0 // Analytics handled by Advertising module
];
$recentRedirects = array_slice($this->redirectModel->getAll(), 0, 5);
View::render('layouts/public-blank.php', [
'page_name' => 'public-redirects-dashboard',
'page_content' => function() use ($stats, $recentRedirects) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'Dashboard',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/public/redirects'],
['label' => 'Dashboard', 'url' => null]
]
]);
View::render('public/redirects/dashboard', [
'stats' => $stats,
'recentRedirects' => $recentRedirects,
'title' => 'Redirects Dashboard'
]);
}
]);
} catch (\Exception $e) {
$this->handleError($e);
}
}
public function redirects(): void
{
try {
$filters = [
'status' => $_GET['status'] ?? '',
'search' => $_GET['search'] ?? ''
];
$redirects = $this->redirectModel->getAll($filters);
View::render('layouts/public-blank.php', [
'page_name' => 'public-redirects-list',
'page_content' => function() use ($redirects, $filters) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'All Redirects',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/public/redirects'],
['label' => 'All Redirects', 'url' => null]
]
]);
View::render('public/redirects/index', [
'redirects' => $redirects,
'filters' => $filters,
'title' => 'All Redirects'
]);
}
]);
} catch (\Exception $e) {
$this->handleError($e);
}
}
public function viewRedirect(int $id): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
header('Location: /public/redirects');
exit;
}
$stats = $this->statsModel->getStatsByRedirect($id);
$recentActivity = $this->statsModel->getRecentActivity($id, 10);
View::render('layouts/public-blank.php', [
'page_name' => 'public-redirects-view',
'page_content' => function() use ($redirect, $stats, $recentActivity) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'View Redirect',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/public/redirects'],
['label' => 'All Redirects', 'url' => '/public/redirects/redirects'],
['label' => 'View Redirect', 'url' => null]
]
]);
View::render('public/redirects/view', [
'redirect' => $redirect,
'stats' => $stats,
'recentActivity' => $recentActivity,
'title' => 'View Redirect'
]);
}
]);
} catch (\Exception $e) {
$this->handleError($e);
}
}
public function stats(): void
{
try {
$startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$endDate = $_GET['end_date'] ?? date('Y-m-d');
// Get overall stats from database
$sql = "SELECT
COUNT(*) as total_clicks,
COUNT(DISTINCT session_id) as unique_clicks,
COUNT(DISTINCT ip_address) as unique_ips,
AVG(response_time_ms) as avg_response_time
FROM redirect_stats";
$overviewStats = $this->statsModel->getDb()->fetch($sql) ?: [
'total_clicks' => 0,
'unique_clicks' => 0,
'unique_ips' => 0,
'avg_response_time' => 0
];
// Get stats by country
$sql = "SELECT
country_code,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE country_code IS NOT NULL AND country_code != ''
GROUP BY country_code
ORDER BY clicks DESC
LIMIT 10";
$countryStats = $this->statsModel->getDb()->fetchAll($sql) ?: [];
// Get stats by device
$sql = "SELECT
device_type,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE device_type IS NOT NULL
GROUP BY device_type
ORDER BY clicks DESC";
$deviceStats = $this->statsModel->getDb()->fetchAll($sql) ?: [];
// Get stats by browser
$sql = "SELECT
browser,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE browser IS NOT NULL AND browser != 'Unknown'
GROUP BY browser
ORDER BY clicks DESC";
$browserStats = $this->statsModel->getDb()->fetchAll($sql) ?: [];
View::render('layouts/public-blank.php', [
'page_name' => 'public-redirects-stats',
'page_content' => function() use ($overviewStats, $countryStats, $deviceStats, $browserStats, $startDate, $endDate) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'Analytics',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/public/redirects'],
['label' => 'Analytics', 'url' => null]
]
]);
View::render('public/redirects/stats/index', [
'overviewStats' => $overviewStats,
'countryStats' => $countryStats,
'deviceStats' => $deviceStats,
'browserStats' => $browserStats,
'startDate' => $startDate,
'endDate' => $endDate,
'title' => 'Analytics'
]);
}
]);
} catch (\Exception $e) {
$this->handleError($e);
}
}
public function statsApi(): void
{
try {
header('Content-Type: application/json');
$startDate = $_GET['start_date'] ?? null;
$endDate = $_GET['end_date'] ?? null;
$trackerId = $_GET['tracker_id'] ?? null;
$country = $_GET['country'] ?? null;
$device = $_GET['device'] ?? null;
$browser = $_GET['browser'] ?? null;
$os = $_GET['os'] ?? null;
// Build WHERE clause for filtering
$whereConditions = [];
$params = [];
if ($startDate && $endDate) {
$whereConditions[] = "DATE(timestamp) BETWEEN ? AND ?";
$params[] = $startDate;
$params[] = $endDate;
} elseif ($startDate) {
$whereConditions[] = "DATE(timestamp) >= ?";
$params[] = $startDate;
} elseif ($endDate) {
$whereConditions[] = "DATE(timestamp) <= ?";
$params[] = $endDate;
}
if ($trackerId) {
$whereConditions[] = "redirect_id = ?";
$params[] = $trackerId;
}
if ($country) {
$whereConditions[] = "country_code = ?";
$params[] = $country;
}
if ($device) {
$whereConditions[] = "device_type = ?";
$params[] = $device;
}
if ($browser) {
$whereConditions[] = "browser = ?";
$params[] = $browser;
}
if ($os) {
$whereConditions[] = "os = ?";
$params[] = $os;
}
$whereClause = empty($whereConditions) ? "" : "WHERE " . implode(" AND ", $whereConditions);
// Get overall stats from database
$sql = "SELECT
COUNT(*) as total_clicks,
COUNT(DISTINCT session_id) as unique_clicks,
COUNT(DISTINCT ip_address) as unique_ips,
AVG(response_time_ms) as avg_response_time
FROM redirect_stats " . $whereClause;
$overviewStats = $this->statsModel->getDb()->fetch($sql, $params) ?: [
'total_clicks' => 0,
'unique_clicks' => 0,
'unique_ips' => 0,
'avg_response_time' => 0
];
// Get stats by country
$countryWhereConditions = array_merge($whereConditions, ["country_code IS NOT NULL", "country_code != ''"]);
$countryWhereClause = "WHERE " . implode(" AND ", $countryWhereConditions);
$sql = "SELECT
country_code,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
$countryWhereClause
GROUP BY country_code
ORDER BY clicks DESC
LIMIT 10";
$countryStats = $this->statsModel->getDb()->fetchAll($sql, $params) ?: [];
// Get stats by device
$deviceWhereConditions = array_merge($whereConditions, ["device_type IS NOT NULL"]);
$deviceWhereClause = empty($deviceWhereConditions) ? "" : "WHERE " . implode(" AND ", $deviceWhereConditions);
$sql = "SELECT
device_type,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
$deviceWhereClause
GROUP BY device_type
ORDER BY clicks DESC";
$deviceStats = $this->statsModel->getDb()->fetchAll($sql, $params) ?: [];
// Get stats by browser
$browserWhereConditions = array_merge($whereConditions, ["browser IS NOT NULL", "browser != 'Unknown'"]);
$browserWhereClause = "WHERE " . implode(" AND ", $browserWhereConditions);
$sql = "SELECT
browser,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
$browserWhereClause
GROUP BY browser
ORDER BY clicks DESC";
$browserStats = $this->statsModel->getDb()->fetchAll($sql, $params) ?: [];
echo json_encode([
'overview' => $overviewStats,
'country' => $countryStats,
'device' => $deviceStats,
'browser' => $browserStats
]);
} catch (\Exception $e) {
http_response_code(500);
echo json_encode(['error' => 'Failed to load statistics']);
}
}
public function processRedirect(string $cuid): void
{
try {
$redirect = $this->redirectModel->getByCuid($cuid);
if (!$redirect) {
http_response_code(404);
echo "Redirect not found";
return;
}
if ($redirect['status'] != 1) {
http_response_code(410);
echo "Redirect is inactive";
return;
}
// Simple redirect - no complex processing needed
$targetUrl = $redirect['target_url'];
// Analytics are handled by the Advertising module
// Just perform the redirect
header("Location: " . $targetUrl, true, (int)$redirect['redirect_type']);
exit;
} catch (\Exception $e) {
http_response_code(500);
echo "Internal server error";
}
}
private function handleError(\Exception $e): void
{
error_log("PublicRedirectsController error: " . $e->getMessage());
http_response_code(500);
echo "Internal server error";
}
}
@@ -0,0 +1,723 @@
<?php
namespace App\Modules\Redirects\Controllers;
use App\Core\BaseController;
use App\Core\Sanitize;
use App\Core\DatabaseManager;
use App\Modules\Redirects\Models\RedirectModel;
use App\Modules\Redirects\Models\RedirectFilterModel;
use App\Modules\Redirects\Models\RedirectStatsModel;
use App\Modules\Redirects\Services\RedirectAutoCreatorService;
class RedirectsApiController extends BaseController
{
private RedirectModel $redirectModel;
private RedirectFilterModel $filterModel;
private RedirectStatsModel $statsModel;
private RedirectAutoCreatorService $autoCreatorService;
public function __construct()
{
parent::__construct();
$this->redirectModel = new RedirectModel();
$this->filterModel = new RedirectFilterModel();
$this->statsModel = new RedirectStatsModel();
$this->autoCreatorService = new RedirectAutoCreatorService();
}
public function create(): void
{
try {
$input = json_decode(file_get_contents('php://input'), true) ?: [];
$data = [
'name' => Sanitize::string($input['name'] ?? ''),
'source_url' => Sanitize::url($input['source_url'] ?? ''),
'target_url' => Sanitize::url($input['target_url'] ?? ''),
'fallback_url' => Sanitize::url($input['fallback_url'] ?? ''),
'status' => (int)($input['status'] ?? 1),
'redirect_type' => Sanitize::string($input['redirect_type'] ?? '302'),
'tracking_enabled' => (int)($input['tracking_enabled'] ?? 1),
'max_clicks' => !empty($input['max_clicks']) ? (int)$input['max_clicks'] : null,
'expires_at' => !empty($input['expires_at']) ? $input['expires_at'] : null,
'created_by' => 1
];
if (empty($data['name']) || empty($data['target_url'])) {
$this->errorResponse('Name and target URL are required', 400);
return;
}
// ✅ Create redirect and associated creative
$success = $this->redirectModel->createWithCreative($data);
if ($success) {
// 🚀 AUTO-CREATE: multisite + campaign + creative
$autoResult = $this->autoCreatorService->createCompleteRedirect($data);
if ($autoResult['success']) {
$this->successResponse([
'redirect_created' => true,
'multisite_created' => $autoResult['site_group_id'],
'campaign_created' => $autoResult['campaign_id'],
'creative_created' => $autoResult['creative_id']
], 'Redirect created successfully with automatic multisite and campaign setup');
} else {
$this->successResponse([], 'Redirect created but multisite setup failed: ' . $autoResult['message']);
}
} else {
$this->errorResponse('Failed to create redirect with creative', 500);
}
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function index(): void
{
try {
$filters = [
'status' => $_GET['status'] ?? '',
'search' => $_GET['search'] ?? ''
];
$redirects = $this->redirectModel->getAll($filters);
$this->successResponse(['redirects' => $redirects], 'Redirects retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function update(int $id): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
$input = json_decode(file_get_contents('php://input'), true) ?: [];
$data = [
'name' => Sanitize::string($input['name'] ?? $redirect['name']),
'source_url' => Sanitize::url($input['source_url'] ?? $redirect['source_url']),
'target_url' => Sanitize::url($input['target_url'] ?? $redirect['target_url']),
'fallback_url' => Sanitize::url($input['fallback_url'] ?? $redirect['fallback_url']),
'status' => (int)($input['status'] ?? $redirect['status']),
'redirect_type' => Sanitize::string($input['redirect_type'] ?? $redirect['redirect_type']),
'tracking_enabled' => (int)($input['tracking_enabled'] ?? $redirect['tracking_enabled']),
'max_clicks' => !empty($input['max_clicks']) ? (int)$input['max_clicks'] : $redirect['max_clicks'],
'expires_at' => !empty($input['expires_at']) ? $input['expires_at'] : $redirect['expires_at']
];
$success = $this->redirectModel->updateWithCreative($id, $data);
if ($success) {
// 🚀 AUTO-UPDATE: Update associated creative via Advertising module
$redirectCreativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
$creativeResult = $redirectCreativeService->updateCreativeFromRedirect($id, $data);
if ($creativeResult) {
$this->successResponse([
'redirect_updated' => true,
'creative_updated' => true
], 'Redirect updated successfully with Advertising module integration');
} else {
$this->successResponse([], 'Redirect updated but Advertising module update failed');
}
} else {
$this->errorResponse('Failed to update redirect with creative', 500);
}
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function show(int $id): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
$this->successResponse(['redirect' => $redirect], 'Redirect retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function delete(int $id): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
$success = $this->redirectModel->deleteWithCreative($id);
if ($success) {
$this->successResponse([], 'Redirect deleted successfully with creative integration');
} else {
$this->errorResponse('Failed to delete redirect with creative', 500);
}
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function getStats(int $id): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
$startDate = $_GET['start_date'] ?? null;
$endDate = $_GET['end_date'] ?? null;
$stats = [
'overview' => $this->statsModel->getStatsByRedirect($id, $startDate, $endDate),
'by_country' => $this->statsModel->getStatsByCountry($id, $startDate, $endDate),
'by_device' => $this->statsModel->getStatsByDevice($id, $startDate, $endDate),
'by_browser' => $this->statsModel->getStatsByBrowser($id, $startDate, $endDate),
'by_hour' => $this->statsModel->getStatsByHour($id, $startDate, $endDate),
'recent_activity' => $this->statsModel->getRecentActivity($id, 10)
];
$this->successResponse($stats, 'Stats retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function getFilters(int $id): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
$filters = $this->filterModel->getByRedirectId($id);
$this->successResponse($filters, 'Filters retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function addFilter(int $id): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
$data = [
'redirect_id' => $id,
'filter_type' => Sanitize::string($_POST['filter_type'] ?? ''),
'filter_value' => Sanitize::string($_POST['filter_value'] ?? ''),
'filter_operator' => Sanitize::string($_POST['filter_operator'] ?? 'equals'),
'filter_value_secondary' => Sanitize::string($_POST['filter_value_secondary'] ?? null),
'priority' => (int)($_POST['priority'] ?? 0),
'is_active' => (int)($_POST['is_active'] ?? 1)
];
if (empty($data['filter_type']) || empty($data['filter_value'])) {
$this->errorResponse('Filter type and value are required', 400);
return;
}
$success = $this->filterModel->create($data);
if ($success) {
$this->successResponse([], 'Filter added successfully');
} else {
$this->errorResponse('Failed to add filter', 500);
}
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function deleteFilter(int $id, int $filterId): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
$success = $this->filterModel->delete($filterId);
if ($success) {
$this->successResponse([], 'Filter deleted successfully');
} else {
$this->errorResponse('Failed to delete filter', 500);
}
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
/**
* Obter os site groups associados a um redirect específico
*/
public function getSiteGroups(int $id): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
// Query para obter os site groups associados
$sql = "
SELECT
rsgm.*,
asg.name as site_group_name,
asg.description as site_group_description,
asg.status as site_group_status,
ac.name as creative_name,
ac.creative_type
FROM redirect_site_group_mapping rsgm
LEFT JOIN advertising_site_groups asg ON rsgm.site_group_id = asg.id
LEFT JOIN advertising_creatives ac ON rsgm.creative_id = ac.id
WHERE rsgm.redirect_id = ?
ORDER BY rsgm.priority DESC, rsgm.created_at DESC
";
$db = DatabaseManager::getInstance();
$siteGroups = $db->fetchAll($sql, [$id]);
$this->successResponse([
'redirect_id' => $id,
'site_groups' => $siteGroups
], 'Site groups retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
/**
* Associar um redirect com um site group
*/
public function associateSiteGroup(int $id): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
$input = json_decode(file_get_contents('php://input'), true) ?: [];
$data = [
'redirect_id' => $id,
'site_group_id' => (int)($input['site_group_id'] ?? 0),
'creative_id' => !empty($input['creative_id']) ? (int)$input['creative_id'] : null,
'mapping_type' => Sanitize::string($input['mapping_type'] ?? 'primary'),
'priority' => (int)($input['priority'] ?? 0),
'geo_targeting' => !empty($input['geo_targeting']) ? json_encode($input['geo_targeting']) : null,
'device_targeting' => !empty($input['device_targeting']) ? json_encode($input['device_targeting']) : null,
'time_targeting' => !empty($input['time_targeting']) ? json_encode($input['time_targeting']) : null,
'traffic_percentage' => (float)($input['traffic_percentage'] ?? 100.00),
'is_active' => (int)($input['is_active'] ?? 1)
];
if (empty($data['site_group_id'])) {
$this->errorResponse('Site group ID is required', 400);
return;
}
// Verificar se o site group existe
$db = DatabaseManager::getInstance();
$siteGroup = $db->fetch("SELECT id FROM advertising_site_groups WHERE id = ?", [$data['site_group_id']]);
if (!$siteGroup) {
$this->errorResponse('Site group not found', 404);
return;
}
// Verificar se já existe uma associação
$existing = $db->fetch("SELECT id FROM redirect_site_group_mapping WHERE redirect_id = ? AND site_group_id = ?", [$id, $data['site_group_id']]);
if ($existing) {
$this->errorResponse('Association already exists', 409);
return;
}
// Inserir a associação
$sql = "
INSERT INTO redirect_site_group_mapping (
redirect_id, site_group_id, creative_id, mapping_type,
priority, geo_targeting, device_targeting, time_targeting,
traffic_percentage, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
";
$success = $db->query($sql, [
$data['redirect_id'], $data['site_group_id'], $data['creative_id'],
$data['mapping_type'], $data['priority'], $data['geo_targeting'],
$data['device_targeting'], $data['time_targeting'], $data['traffic_percentage'],
$data['is_active']
]);
if ($success) {
$this->successResponse([], 'Site group associated successfully');
} else {
$this->errorResponse('Failed to associate site group', 500);
}
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
/**
* Remover a associação de um redirect com um site group
*/
public function removeSiteGroup(int $id, int $mappingId): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
// Verificar se a associação existe e pertence ao redirect
$db = DatabaseManager::getInstance();
$mapping = $db->fetch("SELECT id FROM redirect_site_group_mapping WHERE id = ? AND redirect_id = ?", [$mappingId, $id]);
if (!$mapping) {
$this->errorResponse('Mapping not found', 404);
return;
}
// Remover a associação
$success = $db->query("DELETE FROM redirect_site_group_mapping WHERE id = ?", [$mappingId]);
if ($success) {
$this->successResponse([], 'Site group association removed successfully');
} else {
$this->errorResponse('Failed to remove site group association', 500);
}
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
/**
* Atualizar uma associação existente de um redirect com um site group
*/
public function updateSiteGroup(int $id, int $mappingId): void
{
try {
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
$this->errorResponse('Redirect not found', 404);
return;
}
// Verificar se a associação existe e pertence ao redirect
$db = DatabaseManager::getInstance();
$mapping = $db->fetch("SELECT id FROM redirect_site_group_mapping WHERE id = ? AND redirect_id = ?", [$mappingId, $id]);
if (!$mapping) {
$this->errorResponse('Mapping not found', 404);
return;
}
$input = json_decode(file_get_contents('php://input'), true) ?: [];
$data = [
'creative_id' => !empty($input['creative_id']) ? (int)$input['creative_id'] : null,
'mapping_type' => Sanitize::string($input['mapping_type'] ?? 'primary'),
'priority' => (int)($input['priority'] ?? 0),
'geo_targeting' => !empty($input['geo_targeting']) ? json_encode($input['geo_targeting']) : null,
'device_targeting' => !empty($input['device_targeting']) ? json_encode($input['device_targeting']) : null,
'time_targeting' => !empty($input['time_targeting']) ? json_encode($input['time_targeting']) : null,
'traffic_percentage' => (float)($input['traffic_percentage'] ?? 100.00),
'is_active' => (int)($input['is_active'] ?? 1)
];
// Atualizar a associação
$sql = "
UPDATE redirect_site_group_mapping SET
creative_id = ?, mapping_type = ?, priority = ?,
geo_targeting = ?, device_targeting = ?, time_targeting = ?,
traffic_percentage = ?, is_active = ?
WHERE id = ?
";
$success = $db->query($sql, [
$data['creative_id'], $data['mapping_type'], $data['priority'],
$data['geo_targeting'], $data['device_targeting'], $data['time_targeting'],
$data['traffic_percentage'], $data['is_active'], $mappingId
]);
if ($success) {
$this->successResponse([], 'Site group association updated successfully');
} else {
$this->errorResponse('Failed to update site group association', 500);
}
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function getOverviewStats(): void
{
try {
$startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$endDate = $_GET['end_date'] ?? date('Y-m-d');
// Implementar estatísticas gerais
$stats = [
'total_clicks' => 0,
'unique_clicks' => 0,
'unique_ips' => 0,
'avg_response_time' => 0
];
$this->successResponse($stats, 'Overview stats retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function getStatsByCountry(): void
{
try {
$startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$endDate = $_GET['end_date'] ?? date('Y-m-d');
// Implementar estatísticas por país
$stats = [];
$this->successResponse($stats, 'Country stats retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function getStatsByDevice(): void
{
try {
$startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$endDate = $_GET['end_date'] ?? date('Y-m-d');
// Implementar estatísticas por dispositivo
$stats = [];
$this->successResponse($stats, 'Device stats retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function getStatsByBrowser(): void
{
try {
$startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$endDate = $_GET['end_date'] ?? date('Y-m-d');
// Implementar estatísticas por browser
$stats = [];
$this->successResponse($stats, 'Browser stats retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
public function getStatsByHour(): void
{
try {
$startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$endDate = $_GET['end_date'] ?? date('Y-m-d');
// Implementar estatísticas por hora
$stats = [];
$this->successResponse($stats, 'Hour stats retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
/**
* Get redirects as creatives for Advertising module integration
*/
public function getRedirectCreatives(): void
{
try {
$creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
$redirectCreatives = $creativeService->getAllRedirectCreatives();
$this->successResponse([
'redirect_creatives' => $redirectCreatives,
'total' => count($redirectCreatives)
], 'Redirect creatives retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Server error: ' . $e->getMessage(), 500);
}
}
/**
* Migrate all existing redirects to creatives
*/
public function migrateRedirectsToCreatives(): void
{
try {
$creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
$results = $creativeService->migrateAllRedirects();
$successCount = count(array_filter($results, fn($r) => $r['success']));
$totalCount = count($results);
$this->successResponse([
'migration_results' => $results,
'summary' => [
'total_redirects' => $totalCount,
'successful_migrations' => $successCount,
'failed_migrations' => $totalCount - $successCount
]
], "Migration completed: {$successCount}/{$totalCount} redirects migrated successfully");
} catch (\Exception $e) {
$this->errorResponse('Migration failed: ' . $e->getMessage(), 500);
}
}
public function statsApi(): void
{
try {
header('Content-Type: application/json');
$startDate = $_GET['start_date'] ?? null;
$endDate = $_GET['end_date'] ?? null;
$trackerId = $_GET['tracker_id'] ?? null;
$country = $_GET['country'] ?? null;
$device = $_GET['device'] ?? null;
$browser = $_GET['browser'] ?? null;
$os = $_GET['os'] ?? null;
// Build WHERE clause for filtering
$whereConditions = [];
$params = [];
if ($startDate && $endDate) {
$whereConditions[] = "DATE(timestamp) BETWEEN ? AND ?";
$params[] = $startDate;
$params[] = $endDate;
} elseif ($startDate) {
$whereConditions[] = "DATE(timestamp) >= ?";
$params[] = $startDate;
} elseif ($endDate) {
$whereConditions[] = "DATE(timestamp) <= ?";
$params[] = $endDate;
}
if ($trackerId) {
$whereConditions[] = "redirect_id = ?";
$params[] = $trackerId;
}
if ($country) {
$whereConditions[] = "country_code = ?";
$params[] = $country;
}
if ($device) {
$whereConditions[] = "device_type = ?";
$params[] = $device;
}
if ($browser) {
$whereConditions[] = "browser = ?";
$params[] = $browser;
}
if ($os) {
$whereConditions[] = "os = ?";
$params[] = $os;
}
$whereClause = empty($whereConditions) ? "" : "WHERE " . implode(" AND ", $whereConditions);
// Get overall stats from database
$sql = "SELECT
COUNT(*) as total_clicks,
COUNT(DISTINCT session_id) as unique_clicks,
COUNT(DISTINCT ip_address) as unique_ips,
AVG(response_time_ms) as avg_response_time
FROM redirect_stats " . $whereClause;
$overviewStats = DatabaseManager::getInstance()->fetch($sql, $params) ?: [
'total_clicks' => 0,
'unique_clicks' => 0,
'unique_ips' => 0,
'avg_response_time' => 0
];
// Get stats by country
$countryWhereConditions = array_merge($whereConditions, ["country_code IS NOT NULL", "country_code != ''"]);
$countryWhereClause = "WHERE " . implode(" AND ", $countryWhereConditions);
$sql = "SELECT
country_code,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
$countryWhereClause
GROUP BY country_code
ORDER BY clicks DESC
LIMIT 10";
$countryStats = DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
// Get stats by device
$deviceWhereConditions = array_merge($whereConditions, ["device_type IS NOT NULL"]);
$deviceWhereClause = empty($deviceWhereConditions) ? "" : "WHERE " . implode(" AND ", $deviceWhereConditions);
$sql = "SELECT
device_type,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
$deviceWhereClause
GROUP BY device_type
ORDER BY clicks DESC";
$deviceStats = DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
// Get stats by browser
$browserWhereConditions = array_merge($whereConditions, ["browser IS NOT NULL", "browser != 'Unknown'"]);
$browserWhereClause = "WHERE " . implode(" AND ", $browserWhereConditions);
$sql = "SELECT
browser,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
$browserWhereClause
GROUP BY browser
ORDER BY clicks DESC";
$browserStats = DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
$this->successResponse([
'overview' => $overviewStats,
'by_country' => $countryStats,
'by_device' => $deviceStats,
'by_browser' => $browserStats
], 'Statistics retrieved successfully');
} catch (\Exception $e) {
$this->errorResponse('Failed to load statistics: ' . $e->getMessage(), 500);
}
}
}
@@ -0,0 +1,545 @@
<?php
namespace App\Modules\Redirects\Controllers;
use App\Core\BaseController;
use App\Core\View;
use App\Core\Sanitize;
use App\Core\DatabaseManager;
use App\Core\ErrorReporter;
use App\Modules\Redirects\Models\RedirectModel;
use App\Modules\Redirects\Models\RedirectFilterModel;
use App\Modules\Redirects\Models\RedirectStatsModel;
use App\Modules\Redirects\Services\RedirectProcessor;
class RedirectsController extends BaseController
{
private RedirectModel $redirectModel;
private RedirectFilterModel $filterModel;
private RedirectStatsModel $statsModel;
private RedirectProcessor $processor;
public function __construct()
{
parent::__construct();
// Require authentication for all redirects operations
\App\Core\AuthMiddleware::requireAuth();
$this->redirectModel = new RedirectModel();
$this->filterModel = new RedirectFilterModel();
$this->statsModel = new RedirectStatsModel();
$this->processor = new RedirectProcessor();
}
public function dashboard(): void
{
$stats = [
'total_redirects' => $this->redirectModel->getCount(),
'active_redirects' => $this->redirectModel->getActiveCount(),
'inactive_redirects' => $this->redirectModel->getInactiveCount(),
'recent_redirects' => array_slice($this->redirectModel->getAll(), 0, 5)
];
View::render('layouts/main.php', [
'title' => 'Redirects Dashboard',
'page_name' => 'apps-redirects-dashboard',
'page_content' => function() use ($stats) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'Dashboard',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/redirects'],
['label' => 'Dashboard', 'url' => null]
]
]);
View::render('@redirects/dashboard', ['stats' => $stats, 'title' => 'Redirects Dashboard']);
}
]);
}
public function redirects(): void
{
$filters = [
'status' => Sanitize::string($_GET['status'] ?? ''),
'search' => Sanitize::string($_GET['search'] ?? '')
];
$redirects = $this->redirectModel->getAll($filters);
View::render('layouts/main.php', [
'title' => 'All Redirects',
'page_name' => 'apps-redirects-list',
'page_content' => function() use ($redirects, $filters) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'All Redirects',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/redirects'],
['label' => 'All Redirects', 'url' => null]
]
]);
View::render('@redirects/redirects/index', ['redirects' => $redirects, 'filters' => $filters, 'title' => 'All Redirects']);
}
]);
}
public function createRedirect(): void
{
$config = require __DIR__ . '/../config.php';
View::render('layouts/main.php', [
'title' => 'Create Redirect',
'page_name' => 'apps-redirects-create',
'page_content' => function() use ($config) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'Create Redirect',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/redirects'],
['label' => 'All Redirects', 'url' => '/redirects/redirects'],
['label' => 'Create Redirect', 'url' => null]
]
]);
View::render('@redirects/redirects/create', ['config' => $config, 'title' => 'Create Redirect']);
}
]);
}
public function editRedirect(int $id): void
{
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
header('Location: /redirects/redirects');
exit;
}
$filters = $this->filterModel->getByRedirectId($id);
$config = require __DIR__ . '/../config.php';
View::render('layouts/main.php', [
'title' => 'Edit Redirect',
'page_name' => 'apps-redirects-edit',
'page_content' => function() use ($redirect, $filters, $config) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'Edit Redirect',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/redirects'],
['label' => 'All Redirects', 'url' => '/redirects/redirects'],
['label' => 'Edit Redirect', 'url' => null]
]
]);
View::render('@redirects/redirects/edit', ['redirect' => $redirect, 'filters' => $filters, 'config' => $config, 'title' => 'Edit Redirect']);
}
]);
}
public function viewRedirect(int $id): void
{
$redirect = $this->redirectModel->getById($id);
if (!$redirect) {
header('Location: /redirects/redirects');
exit;
}
$filters = $this->filterModel->getByRedirectId($id);
$stats = $this->statsModel->getStatsByRedirect($id);
$recentActivity = $this->statsModel->getRecentActivity($id);
View::render('layouts/main.php', [
'title' => 'View Redirect',
'page_name' => 'apps-redirects-view',
'page_content' => function() use ($redirect, $filters, $stats, $recentActivity) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'View Redirect',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/redirects'],
['label' => 'All Redirects', 'url' => '/redirects/redirects'],
['label' => 'View Redirect', 'url' => null]
]
]);
View::render('@redirects/redirects/view', ['redirect' => $redirect, 'filters' => $filters, 'stats' => $stats, 'recentActivity' => $recentActivity, 'title' => 'View Redirect']);
}
]);
}
public function stats(): void
{
$startDate = Sanitize::string($_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days')));
$endDate = Sanitize::string($_GET['end_date'] ?? date('Y-m-d'));
$stats = [
'overview' => $this->getOverviewStats($startDate, $endDate),
'by_country' => $this->getStatsByCountry($startDate, $endDate),
'by_device' => $this->getStatsByDevice($startDate, $endDate),
'by_browser' => $this->getStatsByBrowser($startDate, $endDate),
'by_hour' => $this->getStatsByHour($startDate, $endDate)
];
// Get filter options from database
$filterOptions = $this->getFilterOptions();
View::render('layouts/main.php', [
'title' => 'Redirects Analytics',
'page_name' => 'apps-redirects-stats',
'page_content' => function() use ($stats, $startDate, $endDate, $filterOptions) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'Analytics',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/redirects'],
['label' => 'Analytics', 'url' => null]
]
]);
View::render('@redirects/stats/index', [
'stats' => $stats,
'startDate' => $startDate,
'endDate' => $endDate,
'title' => 'Redirects Analytics',
'filterOptions' => $filterOptions
]);
}
]);
}
public function settings(): void
{
View::render('layouts/main.php', [
'title' => 'Redirects Settings',
'page_name' => 'apps-redirects-settings',
'page_content' => function() {
View::render('layouts/page-title.php', [
'pagetitle' => 'Redirects',
'title' => 'Settings',
'breadcrumbs' => [
['label' => 'Home', 'url' => '/'],
['label' => 'Redirects', 'url' => '/redirects'],
['label' => 'Settings', 'url' => null]
]
]);
View::render('@redirects/settings', ['title' => 'Redirects Settings']);
}
]);
}
public function processRedirect(string $cuid): void
{
$startTime = microtime(true);
$redirect = $this->redirectModel->getByCuid($cuid);
if (!$redirect || $redirect['status'] != 1) {
http_response_code(404);
echo 'Redirect not found';
return;
}
// Verificar se expirou
if ($redirect['expires_at'] && strtotime($redirect['expires_at']) < time()) {
http_response_code(410);
echo 'Redirect expired';
return;
}
// Processar redirect com filtros
$targetUrl = $this->processor->processRedirect($redirect);
$responseTime = round((microtime(true) - $startTime) * 1000);
// Registrar estatísticas se ativado
if ($redirect['tracking_enabled']) {
$this->recordStats($redirect['id'], $targetUrl, $responseTime);
}
// Fazer redirect
header("Location: " . $targetUrl);
exit;
}
/**
* API para dados de redirects - para Alpine.js
*/
public function apiRedirects(): void
{
try {
header('Content-Type: application/json');
$db = DatabaseManager::getInstance();
// Query explícita, sem SELECT * e sem dummy data
$redirects = $db->fetchAll(
"SELECT
r.id,
r.cuid,
r.name,
r.source_url,
r.target_url,
r.status,
r.redirect_type,
r.tracking_enabled,
r.created_at,
r.updated_at,
COALESCE(rs.total_clicks, 0) AS total_clicks,
COALESCE(rs.unique_clicks, 0) AS unique_clicks
FROM redirects r
LEFT JOIN (
SELECT
redirect_id,
COUNT(*) AS total_clicks,
COUNT(DISTINCT ip_address) AS unique_clicks
FROM redirect_stats
GROUP BY redirect_id
) rs ON rs.redirect_id = r.id
WHERE r.status >= 0
ORDER BY r.created_at DESC"
) ?: [];
$stats = [
'total' => (int)count($redirects),
'active' => (int)array_sum(array_map(static function(array $r) { return (int)($r['status'] === 'active' || (string)$r['status'] === '1'); }, $redirects)),
'inactive' => (int)array_sum(array_map(static function(array $r) { return (int)($r['status'] === 'inactive' || (string)$r['status'] === '0'); }, $redirects)),
'total_clicks' => (int)array_sum(array_map(static function(array $r) { return (int)($r['total_clicks'] ?? 0); }, $redirects))
];
echo json_encode([
'success' => true,
'data' => [
'redirects' => $redirects,
'stats' => $stats,
'pagination' => [
'page' => 1,
'limit' => count($redirects),
'total' => count($redirects),
'pages' => 1
]
],
'timestamp' => date('Y-m-d H:i:s')
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_redirects']);
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Erro ao carregar redirects',
'timestamp' => date('Y-m-d H:i:s')
]);
}
}
private function getOverviewStats(string $startDate, string $endDate): array
{
try {
$db = \App\Core\DatabaseManager::getInstance();
$sql = "SELECT
COUNT(*) as total_clicks,
COUNT(DISTINCT session_id) as unique_clicks,
COUNT(DISTINCT ip_address) as unique_ips,
COALESCE(AVG(response_time_ms), 0) as avg_response_time
FROM redirect_stats
WHERE DATE(timestamp) BETWEEN ? AND ?";
$result = $db->fetch($sql, [$startDate, $endDate]);
return [
'total_clicks' => (int)($result['total_clicks'] ?? 0),
'unique_clicks' => (int)($result['unique_clicks'] ?? 0),
'unique_ips' => (int)($result['unique_ips'] ?? 0),
'avg_response_time' => round((float)($result['avg_response_time'] ?? 0), 2)
];
} catch (\Exception $e) {
// Fallback para dados vazios se a tabela não existir
return [
'total_clicks' => 0,
'unique_clicks' => 0,
'unique_ips' => 0,
'avg_response_time' => 0
];
}
}
private function getStatsByCountry(string $startDate, string $endDate): array
{
try {
$db = \App\Core\DatabaseManager::getInstance();
$sql = "SELECT
country_code,
country_name,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE DATE(timestamp) BETWEEN ? AND ?
GROUP BY country_code, country_name
ORDER BY clicks DESC
LIMIT 10";
return $db->fetchAll($sql, [$startDate, $endDate]) ?: [];
} catch (\Exception $e) {
return [];
}
}
private function getStatsByDevice(string $startDate, string $endDate): array
{
try {
$db = \App\Core\DatabaseManager::getInstance();
$sql = "SELECT
device_type,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE DATE(timestamp) BETWEEN ? AND ?
GROUP BY device_type
ORDER BY clicks DESC";
return $db->fetchAll($sql, [$startDate, $endDate]) ?: [];
} catch (\Exception $e) {
return [];
}
}
private function getStatsByBrowser(string $startDate, string $endDate): array
{
try {
$db = \App\Core\DatabaseManager::getInstance();
$sql = "SELECT
browser,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE DATE(timestamp) BETWEEN ? AND ?
GROUP BY browser
ORDER BY clicks DESC
LIMIT 10";
return $db->fetchAll($sql, [$startDate, $endDate]) ?: [];
} catch (\Exception $e) {
return [];
}
}
private function getStatsByHour(string $startDate, string $endDate): array
{
try {
$db = \App\Core\DatabaseManager::getInstance();
$sql = "SELECT
hour_of_day,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE DATE(timestamp) BETWEEN ? AND ?
GROUP BY hour_of_day
ORDER BY hour_of_day";
return $db->fetchAll($sql, [$startDate, $endDate]) ?: [];
} catch (\Exception $e) {
return [];
}
}
private function recordStats(int $redirectId, string $targetUrl, int $responseTime): void
{
$data = [
'redirect_id' => $redirectId,
'session_id' => session_id() ?: (string) new \Visus\Cuid2\Cuid2(),
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
'ip_long' => ip2long($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'),
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
'referer' => $_SERVER['HTTP_REFERER'] ?? null,
'country_code' => $_SERVER['HTTP_CF_IPCOUNTRY'] ?? null,
'country_name' => null, // Será preenchido pelo processor
'city' => $_SERVER['HTTP_CF_IPCITY'] ?? null,
'region_code' => $_SERVER['HTTP_CF_IPREGION'] ?? null,
'region_name' => null, // Será preenchido pelo processor
'timezone' => $_SERVER['HTTP_CF_IPTIMEZONE'] ?? null,
'asn' => $_SERVER['HTTP_CF_IPASN'] ?? null,
'isp' => $_SERVER['HTTP_CF_IPISP'] ?? null,
'browser' => null, // Será preenchido pelo processor
'browser_version' => null,
'os' => null, // Será preenchido pelo processor
'os_version' => null,
'device_type' => 'desktop', // Será preenchido pelo processor
'language' => $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null,
'hour_of_day' => (int)date('G'),
'day_of_week' => (int)date('N'),
'month' => (int)date('n'),
'year' => (int)date('Y'),
'response_time_ms' => $responseTime,
'target_url_used' => $targetUrl,
'filter_matched' => null // Será preenchido pelo processor
];
$this->statsModel->create($data);
}
/**
* Get filter options for analytics dropdowns
*/
private function getFilterOptions(): array
{
$db = DatabaseManager::getInstance();
try {
// Get available redirects
$redirects = $db->fetchAll("
SELECT id, name, cuid
FROM redirects
WHERE status = 1
ORDER BY name
");
// Get available countries
$countries = $db->fetchAll("
SELECT DISTINCT country_code, country_name
FROM redirect_stats
ORDER BY country_name
");
// Get available browsers
$browsers = $db->fetchAll("
SELECT DISTINCT browser
FROM redirect_stats
ORDER BY browser
");
// Get available operating systems
$operatingSystems = $db->fetchAll("
SELECT DISTINCT os
FROM redirect_stats
ORDER BY os
");
return [
'redirects' => $redirects ?: [],
'countries' => $countries ?: [],
'browsers' => $browsers ?: [],
'operatingSystems' => $operatingSystems ?: [],
'devices' => [
['type' => 'desktop', 'name' => 'Desktop'],
['type' => 'mobile', 'name' => 'Mobile'],
['type' => 'tablet', 'name' => 'Tablet'],
['type' => 'bot', 'name' => 'Bot']
]
];
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'redirects_filter_options']);
return [
'redirects' => [],
'countries' => [],
'browsers' => [],
'operatingSystems' => [],
'devices' => []
];
}
}
}
@@ -0,0 +1,163 @@
<?php
declare(strict_types=1);
namespace App\Modules\Redirects\Database\Migrations;
use App\Core\Database\Migration;
/**
* Migration: Extend Redirects for Analytics Integration
*
* This migration extends the redirects table to integrate with the analytics system
* while maintaining 100% backward compatibility with existing redirects functionality.
*/
class ExtendRedirectsForAnalytics extends Migration
{
/**
* Run the migration
*/
public function up(): void
{
// Add analytics integration fields to redirects table
$sql = "
ALTER TABLE redirects
ADD COLUMN analytics_enabled BOOLEAN DEFAULT TRUE COMMENT 'Enable analytics integration',
ADD COLUMN analytics_campaign_id BIGINT UNSIGNED NULL COMMENT 'Linked analytics campaign ID',
ADD COLUMN analytics_tracker_id BIGINT UNSIGNED NULL COMMENT 'Linked analytics tracker ID',
ADD COLUMN analytics_metadata JSON NULL COMMENT 'Additional analytics metadata',
ADD COLUMN last_analytics_sync TIMESTAMP NULL COMMENT 'Last analytics sync timestamp',
ADD COLUMN analytics_hash VARCHAR(32) NULL COMMENT 'Hash for analytics sync control'
";
$this->db->query($sql);
// Add indexes for performance
$this->db->query("
ALTER TABLE redirects
ADD INDEX idx_analytics_enabled (analytics_enabled),
ADD INDEX idx_analytics_campaign_id (analytics_campaign_id),
ADD INDEX idx_analytics_tracker_id (analytics_tracker_id)
");
// Create analytics_redirects_mapping table for seamless integration
$this->db->query("
CREATE TABLE IF NOT EXISTS analytics_redirects_mapping (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
redirect_id BIGINT UNSIGNED NOT NULL,
analytics_event_id BIGINT UNSIGNED NULL,
analytics_session_id BIGINT UNSIGNED NULL,
redirect_type ENUM('301', '302', 'meta', 'javascript') NOT NULL DEFAULT '302',
source_url VARCHAR(500) NOT NULL,
target_url VARCHAR(500) NOT NULL,
fallback_url VARCHAR(500) NULL,
filter_matched VARCHAR(100) NULL,
response_time_ms INT UNSIGNED NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_redirect_id (redirect_id),
INDEX idx_analytics_event_id (analytics_event_id),
INDEX idx_analytics_session_id (analytics_session_id),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
// Create analytics_redirects_events table for event tracking
$this->db->query("
CREATE TABLE IF NOT EXISTS analytics_redirects_events (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
redirect_id BIGINT UNSIGNED NOT NULL,
event_type ENUM('redirect', 'click', 'conversion', 'error') NOT NULL DEFAULT 'redirect',
event_data JSON NOT NULL COMMENT 'Event data including geo, device, browser info',
ip_address VARCHAR(45) NOT NULL,
ip_long BIGINT NOT NULL,
session_id VARCHAR(64) NULL,
user_agent TEXT NULL,
referer TEXT NULL,
country_code VARCHAR(2) NULL,
country_name VARCHAR(100) NULL,
city VARCHAR(100) NULL,
region_code VARCHAR(10) NULL,
region_name VARCHAR(100) NULL,
timezone VARCHAR(50) NULL,
browser VARCHAR(50) NULL,
browser_version VARCHAR(20) NULL,
os VARCHAR(50) NULL,
os_version VARCHAR(20) NULL,
device_type ENUM('desktop', 'mobile', 'tablet', 'bot') DEFAULT 'desktop',
language VARCHAR(10) NULL,
hour_of_day TINYINT NOT NULL,
day_of_week TINYINT NOT NULL,
month TINYINT NOT NULL,
year SMALLINT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_redirect_id (redirect_id),
INDEX idx_event_type (event_type),
INDEX idx_ip_long (ip_long),
INDEX idx_session_id (session_id),
INDEX idx_country_code (country_code),
INDEX idx_device_type (device_type),
INDEX idx_browser (browser),
INDEX idx_os (os),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
// Create analytics_redirects_daily table for daily aggregations
$this->db->query("
CREATE TABLE IF NOT EXISTS analytics_redirects_daily (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
redirect_id BIGINT UNSIGNED NOT NULL,
date DATE NOT NULL,
total_redirects INT NOT NULL DEFAULT 0,
total_clicks INT NOT NULL DEFAULT 0,
total_conversions INT NOT NULL DEFAULT 0,
total_errors INT NOT NULL DEFAULT 0,
unique_visitors INT NOT NULL DEFAULT 0,
unique_ips INT NOT NULL DEFAULT 0,
avg_response_time DECIMAL(10,2) NOT NULL DEFAULT 0.00,
bounce_rate DECIMAL(5,2) NOT NULL DEFAULT 0.00,
conversion_rate DECIMAL(5,2) NOT NULL DEFAULT 0.00,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY unique_redirect_date (redirect_id, date),
INDEX idx_redirect_id (redirect_id),
INDEX idx_date (date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
echo "✅ Analytics integration tables created successfully!\n";
}
/**
* Reverse the migration
*/
public function down(): void
{
// Remove analytics fields from redirects table
$this->db->query("
ALTER TABLE redirects
DROP COLUMN analytics_enabled,
DROP COLUMN analytics_campaign_id,
DROP COLUMN analytics_tracker_id,
DROP COLUMN analytics_metadata,
DROP COLUMN last_analytics_sync,
DROP COLUMN analytics_hash
");
// Remove analytics indexes
$this->db->query("
ALTER TABLE redirects
DROP INDEX idx_analytics_enabled,
DROP INDEX idx_analytics_campaign_id,
DROP INDEX idx_analytics_tracker_id
");
// Drop analytics tables
$this->db->query("DROP TABLE IF EXISTS analytics_redirects_mapping");
$this->db->query("DROP TABLE IF EXISTS analytics_redirects_events");
$this->db->query("DROP TABLE IF EXISTS analytics_redirects_daily");
echo "✅ Analytics integration tables removed successfully!\n";
}
}
@@ -0,0 +1,223 @@
<?php
declare(strict_types=1);
namespace App\Modules\Redirects\Database\Migrations;
use App\Core\Database\Migration;
/**
* Migration: Integrate Redirects with Site Groups and Creatives
*
* This migration creates a unified multisites system by integrating redirects
* with the existing advertising site groups and creatives, while maintaining
* the tracker functionality and analytics capabilities.
*/
class IntegrateRedirectsWithSiteGroups extends Migration
{
/**
* Run the migration
*/
public function up(): void
{
// Add site group integration fields to redirects table
$sql = "
ALTER TABLE redirects
ADD COLUMN site_group_id BIGINT UNSIGNED NULL COMMENT 'Foreign key to advertising_site_groups',
ADD COLUMN creative_id BIGINT UNSIGNED NULL COMMENT 'Foreign key to advertising_creatives',
ADD COLUMN multisite_type ENUM('standalone', 'site_group', 'creative_based') DEFAULT 'standalone' COMMENT 'Type of multisite integration',
ADD COLUMN site_group_settings JSON NULL COMMENT 'Site group specific settings and configuration',
ADD COLUMN creative_settings JSON NULL COMMENT 'Creative specific settings and configuration',
ADD COLUMN traffic_weight INT(11) NOT NULL DEFAULT 100 COMMENT 'Traffic distribution weight (0-100)',
ADD COLUMN is_primary_redirect BOOLEAN DEFAULT FALSE COMMENT 'Is this the primary redirect for the site group',
ADD COLUMN multisite_status ENUM('active', 'paused', 'archived', 'testing') DEFAULT 'active' COMMENT 'Multisite specific status'
";
$this->db->query($sql);
// Add indexes for performance
$this->db->query("
ALTER TABLE redirects
ADD INDEX idx_site_group_id (site_group_id),
ADD INDEX idx_creative_id (creative_id),
ADD INDEX idx_multisite_type (multisite_type),
ADD INDEX idx_multisite_status (multisite_status),
ADD INDEX idx_traffic_weight (traffic_weight),
ADD INDEX idx_is_primary_redirect (is_primary_redirect)
");
// Create redirect_site_group_mapping table for advanced multisite management
$this->db->query("
CREATE TABLE IF NOT EXISTS redirect_site_group_mapping (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
redirect_id BIGINT UNSIGNED NOT NULL,
site_group_id BIGINT UNSIGNED NOT NULL,
creative_id BIGINT UNSIGNED NULL,
mapping_type ENUM('primary', 'fallback', 'geo_specific', 'device_specific', 'time_specific') NOT NULL DEFAULT 'primary',
priority INT NOT NULL DEFAULT 0 COMMENT 'Priority for this mapping (higher = more important)',
geo_targeting JSON NULL COMMENT 'Geographic targeting rules',
device_targeting JSON NULL COMMENT 'Device targeting rules',
time_targeting JSON NULL COMMENT 'Time-based targeting rules',
traffic_percentage DECIMAL(5,2) NOT NULL DEFAULT 100.00 COMMENT 'Percentage of traffic for this mapping',
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY unique_redirect_site_group (redirect_id, site_group_id),
INDEX idx_redirect_id (redirect_id),
INDEX idx_site_group_id (site_group_id),
INDEX idx_creative_id (creative_id),
INDEX idx_mapping_type (mapping_type),
INDEX idx_priority (priority),
INDEX idx_is_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='Advanced mapping between redirects, site groups and creatives for multisite management'
");
// Create redirect_multisite_analytics table for unified analytics
$this->db->query("
CREATE TABLE IF NOT EXISTS redirect_multisite_analytics (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
redirect_id BIGINT UNSIGNED NOT NULL,
site_group_id BIGINT UNSIGNED NULL,
creative_id BIGINT UNSIGNED NULL,
date DATE NOT NULL,
total_redirects INT NOT NULL DEFAULT 0,
total_clicks INT NOT NULL DEFAULT 0,
total_conversions INT NOT NULL DEFAULT 0,
unique_visitors INT NOT NULL DEFAULT 0,
unique_ips INT NOT NULL DEFAULT 0,
avg_response_time DECIMAL(10,2) NOT NULL DEFAULT 0.00,
traffic_source VARCHAR(50) NULL COMMENT 'Traffic source (direct, organic, paid, social)',
device_breakdown JSON NULL COMMENT 'Device type breakdown',
geo_breakdown JSON NULL COMMENT 'Geographic breakdown',
conversion_funnel JSON NULL COMMENT 'Conversion funnel data',
revenue_data JSON NULL COMMENT 'Revenue and ROI data',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY unique_multisite_date (redirect_id, site_group_id, creative_id, date),
INDEX idx_redirect_id (redirect_id),
INDEX idx_site_group_id (site_group_id),
INDEX idx_creative_id (creative_id),
INDEX idx_date (date),
INDEX idx_traffic_source (traffic_source)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='Unified analytics for redirects in multisite context'
");
// Create redirect_multisite_templates table for template management
$this->db->query("
CREATE TABLE IF NOT EXISTS redirect_multisite_templates (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
site_group_id BIGINT UNSIGNED NOT NULL,
template_name VARCHAR(255) NOT NULL,
template_type ENUM('redirect', 'landing', 'popup', 'interstitial', 'custom') NOT NULL DEFAULT 'redirect',
template_config JSON NOT NULL COMMENT 'Template configuration and settings',
html_template LONGTEXT NULL COMMENT 'HTML template content',
css_template LONGTEXT NULL COMMENT 'CSS template content',
js_template LONGTEXT NULL COMMENT 'JavaScript template content',
variables_schema JSON NULL COMMENT 'Template variables schema',
is_active BOOLEAN DEFAULT TRUE,
created_by BIGINT UNSIGNED NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_site_group_id (site_group_id),
INDEX idx_template_type (template_type),
INDEX idx_is_active (is_active),
INDEX idx_created_by (created_by)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='Templates for multisite redirects and landing pages'
");
// Add foreign key constraints
try {
$this->db->query("
ALTER TABLE redirects
ADD CONSTRAINT fk_redirects_site_group
FOREIGN KEY (site_group_id) REFERENCES advertising_site_groups(id)
ON DELETE SET NULL ON UPDATE CASCADE
");
echo "✅ Added foreign key constraint to advertising_site_groups\n";
} catch (\Exception $e) {
echo "⚠️ Foreign key constraint to site_groups skipped: " . $e->getMessage() . "\n";
}
try {
$this->db->query("
ALTER TABLE redirects
ADD CONSTRAINT fk_redirects_creative
FOREIGN KEY (creative_id) REFERENCES advertising_creatives(id)
ON DELETE SET NULL ON UPDATE CASCADE
");
echo "✅ Added foreign key constraint to advertising_creatives\n";
} catch (\Exception $e) {
echo "⚠️ Foreign key constraint to creatives skipped: " . $e->getMessage() . "\n";
}
echo "✅ Multisites integration tables created successfully!\n";
echo "🎯 Redirects now integrated with Site Groups and Creatives system\n";
echo "🌐 Unified multisites management system ready\n";
}
/**
* Reverse the migration
*/
public function down(): void
{
// Remove foreign key constraints first
try {
$this->db->query("ALTER TABLE redirects DROP FOREIGN KEY fk_redirects_site_group");
echo "✅ Removed foreign key constraint to site_groups\n";
} catch (\Exception $e) {
echo "⚠️ Foreign key constraint removal skipped: " . $e->getMessage() . "\n";
}
try {
$this->db->query("ALTER TABLE redirects DROP FOREIGN KEY fk_redirects_site_group");
echo "✅ Removed foreign key constraint to creatives\n";
} catch (\Exception $e) {
echo "⚠️ Foreign key constraint removal skipped: " . $e->getMessage() . "\n";
}
// Remove indexes
$this->db->query("
ALTER TABLE redirects
DROP INDEX idx_site_group_id,
DROP INDEX idx_creative_id,
DROP INDEX idx_multisite_type,
DROP INDEX idx_multisite_status,
DROP INDEX idx_traffic_weight,
DROP INDEX idx_is_primary_redirect
");
// Remove columns
$this->db->query("
ALTER TABLE redirects
DROP COLUMN site_group_id,
DROP COLUMN creative_id,
DROP COLUMN multisite_type,
DROP COLUMN site_group_settings,
DROP COLUMN creative_settings,
DROP COLUMN traffic_weight,
DROP COLUMN is_primary_redirect,
DROP COLUMN multisite_status
");
// Drop tables
$this->db->query("DROP TABLE IF EXISTS redirect_site_group_mapping");
$this->db->query("DROP TABLE IF EXISTS redirect_multisite_analytics");
$this->db->query("DROP TABLE IF EXISTS redirect_multisite_templates");
echo "✅ Multisites integration reverted successfully\n";
}
/**
* Get migration description
*/
public function getDescription(): string
{
return "Integrate Redirects with Site Groups and Creatives for unified multisites system";
}
}
@@ -0,0 +1,120 @@
<?php
namespace App\Modules\Redirects\Models;
use App\Core\DatabaseManager;
class RedirectFilterModel
{
private DatabaseManager $db;
public function __construct()
{
$this->db = DatabaseManager::getInstance();
}
public function getByRedirectId(int $redirectId): array
{
$sql = "SELECT * FROM redirect_filters WHERE redirect_id = :redirect_id AND is_active = 1 ORDER BY priority DESC, id ASC";
return $this->db->fetchAll($sql, [':redirect_id' => $redirectId]) ?: [];
}
public function create(array $data): bool
{
$sql = "INSERT INTO redirect_filters (
redirect_id, filter_type, filter_value, filter_operator,
filter_value_secondary, priority, is_active
) VALUES (
?, ?, ?, ?, ?, ?, ?
)";
$params = [
$data['redirect_id'],
$data['filter_type'],
$data['filter_value'],
$data['filter_operator'] ?? 'equals',
$data['filter_value_secondary'] ?? null,
$data['priority'] ?? 0,
(int)($data['is_active'] ?? 1)
];
return $this->db->query($sql, $params) > 0;
}
public function update(int $id, array $data): bool
{
$sql = "UPDATE redirect_filters SET
filter_type = ?, filter_value = ?, filter_operator = ?,
filter_value_secondary = ?, priority = ?, is_active = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?";
$params = [
$data['filter_type'],
$data['filter_value'],
$data['filter_operator'] ?? 'equals',
$data['filter_value_secondary'] ?? null,
$data['priority'] ?? 0,
(int)($data['is_active'] ?? 1),
$id
];
return $this->db->query($sql, $params) > 0;
}
/**
* Soft delete redirect filter (update status to -1)
*/
public function delete(int $id): bool
{
$sql = "UPDATE redirect_filters SET status = '-1', updated_at = CURRENT_TIMESTAMP WHERE id = :id";
return $this->db->query($sql, [':id' => $id]) > 0;
}
/**
* Soft delete redirect filters by redirect ID (update status to -1)
*/
public function deleteByRedirectId(int $redirectId): bool
{
$sql = "UPDATE redirect_filters SET status = '-1', updated_at = CURRENT_TIMESTAMP WHERE redirect_id = :redirect_id";
return $this->db->query($sql, [':redirect_id' => $redirectId]) > 0;
}
public function getFilterTypes(): array
{
return [
'browser' => 'Browser',
'os' => 'Operating System',
'device_type' => 'Device Type',
'country' => 'Country',
'city' => 'City',
'region' => 'Region',
'timezone' => 'Timezone',
'language' => 'Language',
'referer' => 'Referer',
'hour' => 'Hour of Day',
'asn' => 'ASN',
'isp' => 'ISP'
];
}
public function getOperators(): array
{
return [
'equals' => 'Equals',
'contains' => 'Contains',
'starts_with' => 'Starts with',
'ends_with' => 'Ends with',
'regex' => 'Regular Expression',
'in' => 'In list',
'not_in' => 'Not in list',
'greater_than' => 'Greater than',
'less_than' => 'Less than',
'between' => 'Between'
];
}
public function getDb(): DatabaseManager
{
return $this->db;
}
}
+335
View File
@@ -0,0 +1,335 @@
<?php
namespace App\Modules\Redirects\Models;
use App\Core\DatabaseManager;
class RedirectModel
{
private DatabaseManager $db;
public function __construct()
{
$this->db = DatabaseManager::getInstance();
}
public function getAll(array $filters = []): array
{
// ✅ MySQL > PHP: Tudo processado na query para performance
$sql = "SELECT
r.id,
r.cuid,
r.name,
r.source_url,
r.target_url,
r.status,
r.redirect_type,
r.tracking_enabled,
r.created_at,
r.updated_at,
COALESCE(rs.total_clicks, 0) as total_clicks,
COALESCE(rs.unique_clicks, 0) as unique_clicks
FROM redirects r
LEFT JOIN (
SELECT
redirect_id,
COUNT(*) as total_clicks,
COUNT(DISTINCT ip_address) as unique_clicks
FROM redirect_stats
GROUP BY redirect_id
) rs ON rs.redirect_id = r.id
WHERE r.status >= 0";
$params = [];
// ✅ MySQL > PHP: Filtros aplicados na query, não em PHP
if (isset($filters['status']) && $filters['status'] !== '') {
$sql .= " AND r.status = ?";
$params[] = (int)$filters['status'];
}
if (!empty($filters['search'])) {
$sql .= " AND (r.name LIKE ? OR r.source_url LIKE ? OR r.target_url LIKE ?)";
$searchTerm = '%' . $filters['search'] . '%';
$params[] = $searchTerm;
$params[] = $searchTerm;
$params[] = $searchTerm;
}
// ✅ MySQL > PHP: Ordenação na query
$sql .= " ORDER BY r.created_at DESC";
return $this->db->fetchAll($sql, $params) ?: [];
}
public function getById(int $id): ?array
{
// ✅ MySQL > PHP: Query otimizada com JOIN para estatísticas
$sql = "SELECT
r.id,
r.cuid,
r.name,
r.source_url,
r.target_url,
r.fallback_url,
r.status,
r.redirect_type,
r.tracking_enabled,
r.max_clicks,
r.expires_at,
r.created_by,
r.created_at,
r.updated_at,
COALESCE(rs.total_clicks, 0) as total_clicks,
COALESCE(rs.unique_clicks, 0) as unique_clicks
FROM redirects r
LEFT JOIN (
SELECT
redirect_id,
COUNT(*) as total_clicks,
COUNT(DISTINCT ip_address) as unique_clicks
FROM redirect_stats
WHERE redirect_id = ?
GROUP BY redirect_id
) rs ON rs.redirect_id = r.id
WHERE r.id = ? AND r.status >= 0";
$result = $this->db->fetch($sql, [$id, $id]);
return $result ?: null;
}
public function getByCuid(string $cuid): ?array
{
// ✅ MySQL > PHP: Query otimizada para buscar por CUID
$sql = "SELECT
r.id,
r.cuid,
r.name,
r.source_url,
r.target_url,
r.fallback_url,
r.status,
r.redirect_type,
r.tracking_enabled,
r.max_clicks,
r.expires_at,
r.created_by,
r.created_at,
r.updated_at,
COALESCE(rs.total_clicks, 0) as total_clicks,
COALESCE(rs.unique_clicks, 0) as unique_clicks
FROM redirects r
LEFT JOIN (
SELECT
redirect_id,
COUNT(*) as total_clicks,
COUNT(DISTINCT ip_address) as unique_clicks
FROM redirect_stats
WHERE redirect_id = r.id
GROUP BY redirect_id
) rs ON rs.redirect_id = r.id
WHERE r.cuid = ? AND r.status >= 0";
$result = $this->db->fetch($sql, [$cuid]);
return $result ?: null;
}
public function create(array $data): bool
{
$cuid = $this->generateCuid();
$sql = "INSERT INTO redirects (
cuid, name, source_url, target_url, fallback_url,
status, redirect_type, tracking_enabled, max_clicks,
expires_at, created_by
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)";
$params = [
$cuid,
$data['name'] ?? '',
$data['source_url'] ?? '',
$data['target_url'] ?? '',
$data['fallback_url'] ?? null,
(int)($data['status'] ?? 1),
$data['redirect_type'] ?? '302',
(int)($data['tracking_enabled'] ?? 1),
$data['max_clicks'] ?? null,
$data['expires_at'] ?? null,
$data['created_by'] ?? 1
];
return $this->db->query($sql, $params) > 0;
}
public function update(int $id, array $data): bool
{
$sql = "UPDATE redirects SET
name = ?, source_url = ?, target_url = ?, fallback_url = ?,
status = ?, redirect_type = ?, tracking_enabled = ?,
max_clicks = ?, expires_at = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?";
$params = [
$data['name'] ?? '',
$data['source_url'] ?? '',
$data['target_url'] ?? '',
$data['fallback_url'] ?? null,
(int)($data['status'] ?? 1),
$data['redirect_type'] ?? '302',
(int)($data['tracking_enabled'] ?? 1),
$data['max_clicks'] ?? null,
$data['expires_at'] ?? null,
$id
];
return $this->db->query($sql, $params) > 0;
}
public function delete(int $id): bool
{
$sql = "UPDATE redirects SET status = -1 WHERE id = :id";
return $this->db->query($sql, [':id' => $id]) > 0;
}
public function getActiveRedirects(): array
{
return $this->getAll(['status' => 1]);
}
public function getRedirectStats(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
{
$sql = "SELECT
DATE(created_at) as date,
COUNT(*) as total_clicks,
COUNT(DISTINCT ip_address) as unique_clicks,
AVG(response_time) as avg_response_time
FROM redirect_stats
WHERE redirect_id = ?";
$params = [$redirectId];
if ($startDate) {
$sql .= " AND created_at >= ?";
$params[] = $startDate;
}
if ($endDate) {
$sql .= " AND created_at <= ?";
$params[] = $endDate;
}
$sql .= " GROUP BY DATE(created_at) ORDER BY date DESC";
return $this->db->fetchAll($sql, $params) ?: [];
}
public function getCount(): int
{
$result = $this->db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status >= 0");
return (int)($result['count'] ?? 0);
}
public function getCountByStatus(): array
{
$sql = "SELECT status, COUNT(*) as count FROM redirects WHERE status >= 0 GROUP BY status";
return $this->db->fetchAll($sql) ?: [];
}
public function getActiveCount(): int
{
$result = $this->db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status = 1");
return (int)($result['count'] ?? 0);
}
public function getInactiveCount(): int
{
$result = $this->db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status = 0");
return (int)($result['count'] ?? 0);
}
public function getDb(): DatabaseManager
{
return $this->db;
}
/**
* Create redirect and associated creative
*/
public function createWithCreative(array $data): bool
{
return $this->db->transaction(function($db) use ($data) {
// Create redirect
$redirectCreated = $this->create($data);
if (!$redirectCreated) {
return false;
}
// Get the created redirect ID
$redirectId = $db->lastInsertId();
// Create associated creative
$creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
$creativeCreated = $creativeService->createCreativeFromRedirect($data);
if (!$creativeCreated) {
return false;
}
return true;
});
}
/**
* Update redirect and associated creative
*/
public function updateWithCreative(int $id, array $data): bool
{
return $this->db->transaction(function($db) use ($id, $data) {
// Update redirect
$redirectUpdated = $this->update($id, $data);
if (!$redirectUpdated) {
return false;
}
// Update associated creative
$creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
$creativeUpdated = $creativeService->updateCreativeFromRedirect($id, $data);
if (!$creativeUpdated) {
return false;
}
return true;
});
}
/**
* Delete redirect and associated creative
*/
public function deleteWithCreative(int $id): bool
{
return $this->db->transaction(function($db) use ($id) {
// Delete redirect (soft delete)
$redirectDeleted = $this->delete($id);
if (!$redirectDeleted) {
return false;
}
// Delete associated creative (soft delete)
$creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
$creativeDeleted = $creativeService->deleteCreativeByRedirectId($id);
if (!$creativeDeleted) {
return false;
}
return true;
});
}
private function generateCuid(): string
{
return (string) new \Visus\Cuid2\Cuid2();
}
}
+206
View File
@@ -0,0 +1,206 @@
<?php
namespace App\Modules\Redirects\Models;
use App\Core\DatabaseManager;
class RedirectStatsModel
{
private DatabaseManager $db;
public function __construct()
{
$this->db = DatabaseManager::getInstance();
}
public function create(array $data): bool
{
$sql = "INSERT INTO redirect_stats (
redirect_id, session_id, ip_address, ip_long, user_agent, referer,
country_code, country_name, city, region_code, region_name, timezone,
asn, isp, browser, browser_version, os, os_version, device_type,
language, hour_of_day, day_of_week, month, year,
response_time_ms, target_url_used, filter_matched
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)";
$params = [
$data['redirect_id'],
$data['session_id'],
$data['ip_address'],
$data['ip_long'],
$data['user_agent'] ?? null,
$data['referer'] ?? null,
$data['country_code'] ?? null,
$data['country_name'] ?? null,
$data['city'] ?? null,
$data['region_code'] ?? null,
$data['region_name'] ?? null,
$data['timezone'] ?? null,
$data['asn'] ?? null,
$data['isp'] ?? null,
$data['browser'] ?? null,
$data['browser_version'] ?? null,
$data['os'] ?? null,
$data['os_version'] ?? null,
$data['device_type'] ?? 'desktop',
$data['language'] ? substr($data['language'], 0, 10) : null,
$data['hour_of_day'],
$data['day_of_week'],
$data['month'],
$data['year'],
$data['response_time_ms'] ?? null,
$data['target_url_used'] ?? null,
$data['filter_matched'] ?? null
];
return $this->db->query($sql, $params) > 0;
}
public function getStatsByRedirect(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
{
$sql = "SELECT
COUNT(*) as total_clicks,
COUNT(DISTINCT session_id) as unique_clicks,
COUNT(DISTINCT ip_address) as unique_ips,
AVG(response_time_ms) as avg_response_time
FROM redirect_stats
WHERE redirect_id = ?";
$params = [$redirectId];
if ($startDate) {
$sql .= " AND DATE(timestamp) >= ?";
$params[] = $startDate;
}
if ($endDate) {
$sql .= " AND DATE(timestamp) <= ?";
$params[] = $endDate;
}
return $this->db->fetch($sql, $params) ?: [];
}
public function getStatsByCountry(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
{
$sql = "SELECT
country_code, country_name,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE redirect_id = ? AND country_code IS NOT NULL";
$params = [$redirectId];
if ($startDate) {
$sql .= " AND DATE(timestamp) >= ?";
$params[] = $startDate;
}
if ($endDate) {
$sql .= " AND DATE(timestamp) <= ?";
$params[] = $endDate;
}
$sql .= " GROUP BY country_code, country_name ORDER BY clicks DESC";
return $this->db->fetchAll($sql, $params) ?: [];
}
public function getStatsByDevice(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
{
$sql = "SELECT
device_type,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE redirect_id = ? AND device_type IS NOT NULL";
$params = [$redirectId];
if ($startDate) {
$sql .= " AND DATE(timestamp) >= ?";
$params[] = $startDate;
}
if ($endDate) {
$sql .= " AND DATE(timestamp) <= ?";
$params[] = $endDate;
}
$sql .= " GROUP BY device_type ORDER BY clicks DESC";
return $this->db->fetchAll($sql, $params) ?: [];
}
public function getStatsByBrowser(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
{
$sql = "SELECT
browser,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE redirect_id = ? AND browser IS NOT NULL";
$params = [$redirectId];
if ($startDate) {
$sql .= " AND DATE(timestamp) >= ?";
$params[] = $startDate;
}
if ($endDate) {
$sql .= " AND DATE(timestamp) <= ?";
$params[] = $endDate;
}
$sql .= " GROUP BY browser ORDER BY clicks DESC";
return $this->db->fetchAll($sql, $params) ?: [];
}
public function getStatsByHour(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
{
$sql = "SELECT
hour_of_day,
COUNT(*) as clicks,
COUNT(DISTINCT session_id) as unique_clicks
FROM redirect_stats
WHERE redirect_id = ?";
$params = [$redirectId];
if ($startDate) {
$sql .= " AND DATE(timestamp) >= ?";
$params[] = $startDate;
}
if ($endDate) {
$sql .= " AND DATE(timestamp) <= ?";
$params[] = $endDate;
}
$sql .= " GROUP BY hour_of_day ORDER BY hour_of_day";
return $this->db->fetchAll($sql, $params) ?: [];
}
public function getRecentActivity(int $redirectId, int $limit = 10): array
{
$sql = "SELECT
ip_address, user_agent, browser, os, device_type,
country_code, city, timestamp, target_url_used
FROM redirect_stats
WHERE redirect_id = ?
ORDER BY timestamp DESC
LIMIT ?";
return $this->db->fetchAll($sql, [$redirectId, $limit]) ?: [];
}
public function getDb(): DatabaseManager
{
return $this->db;
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace App\Modules\Redirects;
use App\Core\MenuManager;
use App\Core\View;
class Module
{
public static function getConfig(): array
{
return [
'name' => 'Redirects',
'version' => '1.0.0',
'description' => 'Sistema de redirects inteligentes com targeting server-side',
'author' => 'BitReport Unip. LDA',
'enabled' => true,
'dependencies' => ['Core', 'Analytics'],
'features' => [
'redirect_management' => true,
'server_side_targeting' => true,
'geo_targeting' => true,
'device_targeting' => true,
'browser_targeting' => true,
'time_targeting' => true,
'analytics_tracking' => true,
'performance_optimization' => true
]
];
}
public static function registerRoutes($router): void
{
require __DIR__ . '/Routes/web.php';
require __DIR__ . '/Routes/api.php';
require __DIR__ . '/Routes/public.php';
}
public static function registerServices(): void
{
// Registar namespace das views do módulo
View::addNamespace('redirects', __DIR__ . '/Views');
// Registar serviços do módulo no ServiceContainer
$container = \App\Core\ServiceContainer::getInstance();
// Registar modelos
$container->registerModuleService('Redirects', 'model.RedirectModel', function() {
return new \App\Modules\Redirects\Models\RedirectModel();
}, true);
$container->registerModuleService('Redirects', 'model.RedirectFilterModel', function() {
return new \App\Modules\Redirects\Models\RedirectFilterModel();
}, true);
$container->registerModuleService('Redirects', 'model.RedirectStatsModel', function() {
return new \App\Modules\Redirects\Models\RedirectStatsModel();
}, true);
// Registar serviços
if (file_exists(__DIR__ . '/Services/RedirectProcessor.php')) {
require_once __DIR__ . '/Services/RedirectProcessor.php';
$container->registerModuleService('Redirects', 'RedirectProcessor', function() {
return new \App\Modules\Redirects\Services\RedirectProcessor();
}, true);
}
}
public static function registerMenu(): void
{
// Compatibilidade: não faz nada, menu já registado via menu.php
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
use App\Core\Router;
use App\Modules\Redirects\Controllers\RedirectsApiController;
/** @var Router $router */
// Stats API endpoint (deve vir ANTES das rotas com {id} para evitar conflitos)
$router->get('/api/redirects/stats', [RedirectsApiController::class, 'statsApi']);
// Redirect creatives endpoint para integração com Advertising module (deve vir ANTES das rotas com {id})
$router->get('/api/redirects/creatives', [RedirectsApiController::class, 'getRedirectCreatives']);
$router->post('/api/redirects/creatives/migrate', [RedirectsApiController::class, 'migrateRedirectsToCreatives']);
// Dados dinâmicos para formulários de redirects
$router->get('/api/redirects/types', [RedirectsApiController::class, 'getRedirectTypes']);
$router->get('/api/redirects/statuses', [RedirectsApiController::class, 'getStatuses']);
$router->get('/api/redirects/filter-types', [RedirectsApiController::class, 'getFilterTypes']);
$router->get('/api/redirects/filter-operators', [RedirectsApiController::class, 'getFilterOperators']);
// Settings API endpoint
$router->get('/api/redirects/settings', [RedirectsApiController::class, 'getSettings']);
$router->post('/api/redirects/settings', [RedirectsApiController::class, 'updateSettings']);
// CRUD endpoints
$router->get('/api/redirects', [RedirectsApiController::class, 'index']);
$router->post('/api/redirects', [RedirectsApiController::class, 'create']);
$router->get('/api/redirects/{id}', [RedirectsApiController::class, 'show']);
$router->put('/api/redirects/{id}', [RedirectsApiController::class, 'update']);
$router->delete('/api/redirects/{id}', [RedirectsApiController::class, 'delete']);
// Stats endpoints por redirect específico
$router->get('/api/redirects/{id}/stats', [RedirectsApiController::class, 'getStats']);
$router->get('/api/redirects/{id}/filters', [RedirectsApiController::class, 'getFilters']);
$router->post('/api/redirects/{id}/filters', [RedirectsApiController::class, 'addFilter']);
$router->delete('/api/redirects/{id}/filters/{filterId}', [RedirectsApiController::class, 'deleteFilter']);
// Site groups endpoint para integração com multisites
$router->get('/api/redirects/{id}/site-groups', [RedirectsApiController::class, 'getSiteGroups']);
$router->post('/api/redirects/{id}/site-groups', [RedirectsApiController::class, 'associateSiteGroup']);
$router->put('/api/redirects/{id}/site-groups/{mappingId}', [RedirectsApiController::class, 'updateSiteGroup']);
$router->delete('/api/redirects/{id}/site-groups/{mappingId}', [RedirectsApiController::class, 'removeSiteGroup']);
+12
View File
@@ -0,0 +1,12 @@
<?php
use App\Modules\Redirects\Controllers\PublicRedirectsController;
// Rotas públicas do módulo de redirects
$router->get('/public/redirects', [PublicRedirectsController::class, 'dashboard']);
$router->get('/public/redirects/redirects', [PublicRedirectsController::class, 'redirects']);
$router->get('/public/redirects/redirects/{int:id}', [PublicRedirectsController::class, 'viewRedirect']);
$router->get('/public/redirects/stats', [PublicRedirectsController::class, 'stats']);
$router->get('/public/redirects/stats/api', [PublicRedirectsController::class, 'statsApi']);
// Rota pública para processar redirects (sem autenticação)
$router->get('/r/{cuid}', [PublicRedirectsController::class, 'processRedirect']);
+17
View File
@@ -0,0 +1,17 @@
<?php
use App\Modules\Redirects\Controllers\RedirectsController;
// Rotas do módulo de redirects
$router->get('/redirects', [RedirectsController::class, 'dashboard']);
$router->get('/redirects/api', [RedirectsController::class, 'apiRedirects']);
$router->get('/redirects/stats', [RedirectsController::class, 'stats']);
$router->get('/redirects/settings', [RedirectsController::class, 'settings']);
$router->get('/redirects/create', [RedirectsController::class, 'createRedirect']); // Shortcut route
$router->get('/redirects/redirects', [RedirectsController::class, 'redirects']);
$router->get('/redirects/redirects/create', [RedirectsController::class, 'createRedirect']);
$router->get('/redirects/edit/{int:id}', [RedirectsController::class, 'editRedirect']); // Shortcut route
$router->get('/redirects/view/{int:id}', [RedirectsController::class, 'viewRedirect']); // Shortcut route
$router->get('/redirects/redirects/{int:id}/edit', [RedirectsController::class, 'editRedirect']);
$router->get('/redirects/redirects/{int:id}', [RedirectsController::class, 'viewRedirect']);
@@ -0,0 +1,245 @@
<?php
namespace App\Modules\Redirects\Services;
use App\Core\DatabaseManager;
use App\Core\ErrorReporter;
use Visus\Cuid2\Cuid2;
class RedirectAutoCreatorService
{
private DatabaseManager $db;
public function __construct()
{
$this->db = DatabaseManager::getInstance();
}
/**
* Create a complete redirect setup: multisite + campaign + creative
*/
public function createCompleteRedirect(array $redirectData): array
{
try {
return $this->db->transaction(function() use ($redirectData) {
// 1. Extract domain from source URL
$domain = $this->extractDomain($redirectData['source_url']);
if (!$domain) {
throw new \Exception("Invalid source URL");
}
// 2. Create or get site group (multisite)
$siteGroupId = $this->createOrGetSiteGroup($domain);
// 3. Create or get campaign
$campaignId = $this->createOrGetCampaign($domain, $siteGroupId);
// 4. Create creative
$creativeId = $this->createCreative($redirectData, $campaignId);
// 5. Associate creative with campaign
$this->associateCreativeWithCampaign($creativeId, $campaignId);
return [
'success' => true,
'site_group_id' => $siteGroupId,
'campaign_id' => $campaignId,
'creative_id' => $creativeId,
'message' => 'Redirect created successfully with multisite and campaign'
];
});
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'redirect_auto_creation',
'redirect_data' => $redirectData
]);
return [
'success' => false,
'message' => 'Failed to create redirect: ' . $e->getMessage()
];
}
}
/**
* Extract domain from URL
*/
private function extractDomain(string $url): ?string
{
if (preg_match('/(?:https?:\/\/)?(?:www\.)?([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/', $url, $matches)) {
return $matches[1];
}
return null;
}
/**
* Create or get existing site group
*/
private function createOrGetSiteGroup(string $domain): int
{
// Check if site group already exists
$existing = $this->db->fetch(
"SELECT id FROM advertising_site_groups WHERE name LIKE ? OR alias LIKE ?",
["%$domain%", "%$domain%"]
);
if ($existing) {
return $existing['id'];
}
// Create new site group
$siteGroupData = [
'cuid' => (new Cuid2())->toString(),
'name' => "Redirects - $domain",
'alias' => "redirects_" . str_replace(['.', '-'], '_', $domain),
'status' => 1
];
$sql = "INSERT INTO advertising_site_groups (cuid, name, alias, status) VALUES (?, ?, ?, ?)";
$this->db->query($sql, [$siteGroupData['cuid'], $siteGroupData['name'], $siteGroupData['alias'], $siteGroupData['status']]);
return $this->db->lastInsertId();
}
/**
* Create or get existing campaign
*/
private function createOrGetCampaign(string $domain, int $siteGroupId): int
{
// Check if campaign already exists
$existing = $this->db->fetch(
"SELECT id FROM advertising_campaigns WHERE name LIKE ? AND site_group_id = ?",
["%$domain%", $siteGroupId]
);
if ($existing) {
return $existing['id'];
}
// Create new campaign
$campaignData = [
'cuid' => (new Cuid2())->toString(),
'name' => "Redirects - $domain",
'site_group_id' => $siteGroupId,
'status' => 1,
'type' => 'banner',
'timezone' => 'UTC',
'frequency_period' => 'day',
'expire_hours' => 24.00,
'expire_mobile_hours' => 24.00,
'allow_close' => 1,
'created_by' => 1
];
$sql = "INSERT INTO advertising_campaigns (
cuid, name, site_group_id, status, type, timezone,
frequency_period, expire_hours, expire_mobile_hours, allow_close, created_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$this->db->query($sql, [
$campaignData['cuid'], $campaignData['name'], $campaignData['site_group_id'],
$campaignData['status'], $campaignData['type'], $campaignData['timezone'],
$campaignData['frequency_period'], $campaignData['expire_hours'],
$campaignData['expire_mobile_hours'], $campaignData['allow_close'], $campaignData['created_by']
]);
return $this->db->lastInsertId();
}
/**
* Create creative from redirect data
*/
private function createCreative(array $redirectData, int $campaignId): string
{
$creativeData = [
'cuid' => (new Cuid2())->toString(),
'name' => $redirectData['name'],
'description' => "Redirect from {$redirectData['source_url']} to {$redirectData['target_url']}",
'view_url' => $redirectData['target_url'],
'creative_type' => 'redirect',
'is_active' => $redirectData['status'] ? 1 : 0,
'width' => 300,
'height' => 250,
'file_name' => "redirect_{$redirectData['name']}.html",
'file_path' => "/redirects/redirect_{$redirectData['name']}.html",
'file_size' => 1024,
'mime_type' => 'text/html'
];
$sql = "INSERT INTO advertising_creatives (
cuid, name, description, view_url, creative_type, is_active,
width, height, file_name, file_path, file_size, mime_type
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$this->db->query($sql, [
$creativeData['cuid'], $creativeData['name'], $creativeData['description'],
$creativeData['view_url'], $creativeData['creative_type'], $creativeData['is_active'],
$creativeData['width'], $creativeData['height'], $creativeData['file_name'],
$creativeData['file_path'], $creativeData['file_size'], $creativeData['mime_type']
]);
return $creativeData['cuid'];
}
/**
* Associate creative with campaign
*/
private function associateCreativeWithCampaign(string $creativeId, int $campaignId): void
{
$sql = "INSERT INTO advertising_campaign_trackers (campaign_id, tracker_id, format_id, country, order_position)
VALUES (?, (SELECT id FROM advertising_creatives WHERE cuid = ?), 1, 'PT', 0)";
$this->db->query($sql, [$campaignId, $creativeId]);
}
/**
* Update existing redirect with new creative
*/
public function updateRedirectCreative(int $redirectId, array $redirectData): array
{
try {
return $this->db->transaction(function() use ($redirectId, $redirectData) {
// Find existing creative by redirect ID
$creative = $this->db->fetch(
"SELECT c.cuid, c.id FROM advertising_creatives c
WHERE c.description LIKE ? AND c.creative_type = 'redirect'
ORDER BY c.created_at DESC LIMIT 1",
["%Redirect from " . $redirectData['source_url'] . "%"]
);
if (!$creative) {
throw new \Exception("Creative not found for redirect ID $redirectId");
}
// Update creative
$sql = "UPDATE advertising_creatives SET
name = ?, view_url = ?, is_active = ?,
description = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?";
$this->db->query($sql, [
$redirectData['name'],
$redirectData['target_url'],
$redirectData['status'] ? 1 : 0,
"Redirect from {$redirectData['source_url']} to {$redirectData['target_url']}",
$creative['id']
]);
return [
'success' => true,
'creative_id' => $creative['cuid'],
'message' => 'Redirect updated successfully'
];
});
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'redirect_update',
'redirect_id' => $redirectId,
'redirect_data' => $redirectData
]);
return [
'success' => false,
'message' => 'Failed to update redirect: ' . $e->getMessage()
];
}
}
}
@@ -0,0 +1,203 @@
<?php
namespace App\Modules\Redirects\Services;
use App\Core\DatabaseManager;
use App\Modules\Redirects\Models\RedirectModel;
/**
* Service to integrate redirects as creatives in the Advertising module
*
* This service transforms redirects into creatives of type "redirect"
* using the standard creative fields, not custom redirect fields
*/
class RedirectCreativeService
{
private DatabaseManager $db;
private RedirectModel $redirectModel;
public function __construct()
{
$this->db = DatabaseManager::getInstance();
$this->redirectModel = new RedirectModel();
}
/**
* Create a creative from a redirect
*/
public function createCreativeFromRedirect(array $redirectData): bool
{
// Generate unique CUID for creative
$cuid = $this->generateCuid();
// Create creative using standard fields
$sql = "INSERT INTO advertising_creatives (
cuid, name, file_name, file_path, file_size, mime_type,
width, height, alt_text, is_active, description,
creative_type, view_url, target_country
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)";
$params = [
$cuid,
$redirectData['name'],
$this->generateFileName($redirectData['name']),
'/redirects/' . $cuid . '.html', // Virtual file path
1024, // Standard size for redirects
'text/html',
300, // Standard width
250, // Standard height
'Redirect: ' . $redirectData['name'],
1, // Active
'Redirect from ' . $redirectData['source_url'] . ' to ' . $redirectData['target_url'],
'redirect', // Creative type
$redirectData['target_url'], // View URL = target URL
null // Target country (can be set later)
];
return $this->db->query($sql, $params) > 0;
}
/**
* Update a creative when redirect is updated
*/
public function updateCreativeFromRedirect(int $redirectId, array $redirectData): bool
{
// Find the creative associated with this redirect
$creative = $this->getCreativeByRedirectId($redirectId);
if (!$creative) {
return false;
}
$sql = "UPDATE advertising_creatives SET
name = ?,
description = ?,
view_url = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?";
$params = [
$redirectData['name'],
'Redirect from ' . $redirectData['source_url'] . ' to ' . $redirectData['target_url'],
$redirectData['target_url'],
$creative['id']
];
return $this->db->query($sql, $params) > 0;
}
/**
* Migrate all existing redirects to creatives
*/
public function migrateAllRedirects(): array
{
$results = [];
// Get all redirects that don't have associated creatives
$sql = "SELECT r.* FROM redirects r
LEFT JOIN advertising_creatives ac ON ac.creative_type = 'redirect'
AND ac.description LIKE CONCAT('%Redirect from ', r.id, '%')
WHERE r.status >= 0 AND ac.id IS NULL";
$redirects = $this->db->fetchAll($sql);
foreach ($redirects as $redirect) {
try {
$success = $this->createCreativeFromRedirect($redirect);
$results[] = [
'redirect_id' => $redirect['id'],
'redirect_name' => $redirect['name'],
'success' => $success,
'message' => $success ? 'Creative created successfully' : 'Failed to create creative'
];
} catch (\Exception $e) {
$results[] = [
'redirect_id' => $redirect['id'],
'redirect_name' => $redirect['name'],
'success' => false,
'message' => 'Error: ' . $e->getMessage()
];
}
}
return $results;
}
/**
* Get creative by redirect ID
*/
public function getCreativeByRedirectId(int $redirectId): ?array
{
$sql = "SELECT * FROM advertising_creatives
WHERE creative_type = 'redirect'
AND description LIKE ?";
$searchTerm = '%Redirect from ' . $redirectId . '%';
return $this->db->fetch($sql, [$searchTerm]) ?: null;
}
/**
* Get all redirect creatives
*/
public function getAllRedirectCreatives(): array
{
$sql = "SELECT * FROM advertising_creatives
WHERE creative_type = 'redirect'
AND is_active = 1
ORDER BY created_at DESC";
return $this->db->fetchAll($sql) ?: [];
}
/**
* Delete creative when redirect is deleted
*/
public function deleteCreativeByRedirectId(int $redirectId): bool
{
$creative = $this->getCreativeByRedirectId($redirectId);
if (!$creative) {
return false;
}
$sql = "UPDATE advertising_creatives SET
is_active = 0,
deleted_at = CURRENT_TIMESTAMP
WHERE id = ?";
return $this->db->query($sql, [$creative['id']]) > 0;
}
/**
* Generate unique CUID for creative
*/
private function generateCuid(): string
{
return 'creative_' . uniqid() . '_' . time();
}
/**
* Generate file name for creative
*/
private function generateFileName(string $name): string
{
return 'redirect_' . preg_replace('/[^a-zA-Z0-9]/', '_', $name) . '.html';
}
/**
* Get redirect statistics for creative
*/
public function getRedirectStatsForCreative(int $creativeId): array
{
$creative = $this->db->fetch("SELECT * FROM advertising_creatives WHERE id = ?", [$creativeId]);
if (!$creative || $creative['creative_type'] !== 'redirect') {
return [];
}
// Extract redirect ID from description or use creative ID as reference
// This is a simplified approach - in production you might want a proper mapping table
$redirectId = $creativeId; // Simplified for now
return $this->redirectModel->getRedirectStats($redirectId);
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Modules\Redirects\Services;
/**
* Simplified RedirectProcessor - redirects are just creatives
* No complex filtering needed, just return target URL
*/
class RedirectProcessor
{
public function processRedirect(array $redirect): string
{
// Redirects are simple creatives, just return target URL
// Analytics and targeting are handled by the Advertising module
return $redirect['target_url'];
}
}
@@ -0,0 +1,35 @@
<!-- Template para filtros dinâmicos -->
<template id="filter-row-template">
<div class="filter-row row mb-3" data-filter-index="{{INDEX}}">
<div class="col-md-4">
<div class="mb-3">
<label for="filter_type_{{INDEX}}" class="form-label">Filter Type *</label>
<select class="form-select" id="filter_type_{{INDEX}}" name="filters[{{INDEX}}][type]" required>
<option value="">Select filter type...</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="mb-3">
<label for="filter_operator_{{INDEX}}" class="form-label">Operator *</label>
<select class="form-select" id="filter_operator_{{INDEX}}" name="filters[{{INDEX}}][operator]" required>
<option value="">Select operator...</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="mb-3">
<label for="filter_value_{{INDEX}}" class="form-label">Value *</label>
<input type="text" class="form-control" id="filter_value_{{INDEX}}" name="filters[{{INDEX}}][value]" required>
</div>
</div>
<div class="col-md-1">
<div class="mb-3">
<label class="form-label">&nbsp;</label>
<button type="button" class="btn btn-danger remove-filter" title="Remove Filter">
<i class="ri-delete-bin-line"></i>
</button>
</div>
</div>
</div>
</template>
+288
View File
@@ -0,0 +1,288 @@
<?php
/**
* Redirects Dashboard
*
* @var array $stats Statistics data
* @var string $title Page title
*/
?>
<!-- Stats Cards -->
<div class="row">
<div class="col-xl-3 col-md-6">
<div class="card mini-stats-wid">
<div class="card-body">
<div class="d-flex">
<div class="flex-grow-1">
<p class="text-muted fw-medium">Total Redirects</p>
<h4 class="mb-0"><?= number_format($stats['total_redirects']) ?></h4>
</div>
<div class="flex-shrink-0 align-self-center">
<div class="mini-stat-icon avatar-sm rounded-circle bg-primary align-self-center">
<span class="avatar-title">
<i class="ri-link font-size-24"></i>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-6">
<div class="card mini-stats-wid">
<div class="card-body">
<div class="d-flex">
<div class="flex-grow-1">
<p class="text-muted fw-medium">Active Redirects</p>
<h4 class="mb-0"><?= number_format($stats['active_redirects']) ?></h4>
</div>
<div class="flex-shrink-0 align-self-center">
<div class="mini-stat-icon avatar-sm rounded-circle bg-success align-self-center">
<span class="avatar-title">
<i class="ri-check-line font-size-24"></i>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-6">
<div class="card mini-stats-wid">
<div class="card-body">
<div class="d-flex">
<div class="flex-grow-1">
<p class="text-muted fw-medium">Inactive Redirects</p>
<h4 class="mb-0"><?= number_format($stats['inactive_redirects']) ?></h4>
</div>
<div class="flex-shrink-0 align-self-center">
<div class="mini-stat-icon avatar-sm rounded-circle bg-warning align-self-center">
<span class="avatar-title">
<i class="ri-pause-line font-size-24"></i>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-6">
<div class="card mini-stats-wid">
<div class="card-body">
<div class="d-flex">
<div class="flex-grow-1">
<p class="text-muted fw-medium">Total Clicks</p>
<h4 class="mb-0">0</h4>
</div>
<div class="flex-shrink-0 align-self-center">
<div class="mini-stat-icon avatar-sm rounded-circle bg-info align-self-center">
<span class="avatar-title">
<i class="ri-mouse-line font-size-24"></i>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Quick Actions -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title mb-4">Quick Actions</h4>
<div class="row">
<div class="col-md-3">
<a href="/redirects/redirects/create" class="btn btn-primary w-100 mb-3">
<i class="ri-add-line me-2"></i>Create Redirect
</a>
</div>
<div class="col-md-3">
<a href="/redirects/redirects" class="btn btn-outline-primary w-100 mb-3">
<i class="ri-list-check me-2"></i>View All Redirects
</a>
</div>
<div class="col-md-3">
<a href="/redirects/stats" class="btn btn-outline-info w-100 mb-3">
<i class="ri-bar-chart-line me-2"></i>Analytics
</a>
</div>
<div class="col-md-3">
<a href="/redirects/settings" class="btn btn-outline-secondary w-100 mb-3">
<i class="ri-settings-3-line me-2"></i>Settings
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Recent Redirects -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="d-flex align-items-center mb-4">
<h4 class="card-title mb-0">Recent Redirects</h4>
<div class="flex-grow-1"></div>
<a href="/redirects/redirects" class="btn btn-sm btn-outline-primary">View All</a>
</div>
<?php if (empty($stats['recent_redirects'])): ?>
<div class="text-center py-4">
<i class="ri-link font-size-48 text-muted"></i>
<h5 class="mt-3 text-muted">No redirects yet</h5>
<p class="text-muted">Create your first redirect to get started</p>
<a href="/redirects/redirects/create" class="btn btn-primary">Create Redirect</a>
</div>
<?php else: ?>
<div class="table-responsive">
<table class="table table-centered table-nowrap mb-0">
<thead>
<tr>
<th>Name</th>
<th>Target URL</th>
<th>Status</th>
<th>Created</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($stats['recent_redirects'] as $redirect): ?>
<tr>
<td>
<div class="d-flex align-items-center">
<div class="avatar-sm bg-light rounded-circle me-3">
<span class="avatar-title">
<i class="ri-link font-size-16"></i>
</span>
</div>
<div>
<h6 class="mb-0"><?= htmlspecialchars($redirect['name']) ?></h6>
<small class="text-muted"><?= htmlspecialchars($redirect['id']) ?></small>
</div>
</div>
</td>
<td>
<span class="text-truncate d-inline-block" style="max-width: 200px;" title="<?= htmlspecialchars($redirect['target_url']) ?>">
<?= htmlspecialchars($redirect['target_url']) ?>
</span>
</td>
<td>
<?php if ($redirect['status'] == 1): ?>
<span class="badge bg-success">Active</span>
<?php elseif ($redirect['status'] == 0): ?>
<span class="badge bg-warning">Inactive</span>
<?php else: ?>
<span class="badge bg-danger">Deleted</span>
<?php endif; ?>
</td>
<td>
<?= date('M j, Y', strtotime($redirect['created_at'])) ?>
</td>
<td>
<div class="dropdown">
<a href="#" class="dropdown-toggle card-drop" data-bs-toggle="dropdown" aria-expanded="false">
<i class="ri-more-fill"></i>
</a>
<ul class="dropdown-menu dropdown-menu-end">
<li><a class="dropdown-item" href="/redirects/redirects/<?= $redirect['id'] ?>"><i class="ri-eye-line me-2"></i>View</a></li>
<li><a class="dropdown-item" href="/redirects/redirects/<?= $redirect['id'] ?>/edit"><i class="ri-pencil-line me-2"></i>Edit</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item text-danger" href="#" onclick="deleteRedirect(<?= $redirect['id'] ?>)"><i class="ri-delete-bin-line me-2"></i>Delete</a></li>
</ul>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<!-- How it works -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title mb-4">How Redirects Work</h4>
<div class="row">
<div class="col-md-4">
<div class="text-center">
<div class="avatar-sm bg-light rounded-circle mx-auto mb-3">
<span class="avatar-title">
<i class="ri-link font-size-24 text-primary"></i>
</span>
</div>
<h5>1. Create Redirect</h5>
<p class="text-muted">Set up your source and target URLs with optional filters</p>
</div>
</div>
<div class="col-md-4">
<div class="text-center">
<div class="avatar-sm bg-light rounded-circle mx-auto mb-3">
<span class="avatar-title">
<i class="ri-filter-3-line font-size-24 text-success"></i>
</span>
</div>
<h5>2. Add Filters</h5>
<p class="text-muted">Target by country, browser, device, time, and more</p>
</div>
</div>
<div class="col-md-4">
<div class="text-center">
<div class="avatar-sm bg-light rounded-circle mx-auto mb-3">
<span class="avatar-title">
<i class="ri-bar-chart-line font-size-24 text-info"></i>
</span>
</div>
<h5>3. Track Analytics</h5>
<p class="text-muted">Monitor performance and user behavior in real-time</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function deleteRedirect(id) {
if (confirm('Are you sure you want to delete this redirect?')) {
fetch(`/api/redirects/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
location.reload();
} else {
alert('Error: ' + data.error);
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while deleting the redirect');
});
}
}
</script>
+359
View File
@@ -0,0 +1,359 @@
<?php
/**
* Create Redirect
*
* @var array $config Module configuration
* @var string $title Page title
*/
?>
<!-- Include filter template -->
<?php include __DIR__ . '/../components/filter-template.php'; ?>
<!-- Create Form -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<form id="redirectForm" class="needs-validation" x-data="redirectCreate()" x-init="init()" novalidate>
<div class="row">
<!-- Basic Information -->
<div class="col-md-8">
<h5 class="mb-3">Basic Information</h5>
<div class="mb-3">
<label for="name" class="form-label">Redirect Name *</label>
<input type="text" class="form-control" id="name" name="name" required>
<div class="invalid-feedback">Please provide a redirect name.</div>
</div>
<div class="mb-3">
<label for="source_url" class="form-label">Source URL</label>
<input type="url" class="form-control" id="source_url" name="source_url" placeholder="https://example.com/old-page">
<div class="form-text">Optional: The original URL that will be redirected</div>
</div>
<div class="mb-3">
<label for="target_url" class="form-label">Target URL *</label>
<input type="url" class="form-control" id="target_url" name="target_url" required>
<div class="invalid-feedback">Please provide a valid target URL.</div>
</div>
<div class="mb-3">
<label for="fallback_url" class="form-label">Fallback URL</label>
<input type="url" class="form-control" id="fallback_url" name="fallback_url" placeholder="https://example.com/fallback">
<div class="form-text">Optional: URL to redirect to when filters don't match</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="redirect_type" class="form-label" data-key="redirects.types.title">Redirect Type</label>
<select class="form-select" id="redirect_type" name="redirect_type">
<option value="" data-key="common.select">Selecionar tipo</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="status" class="form-label" data-key="redirects.status.title">Status</label>
<select class="form-select" id="status" name="status">
<option value="" data-key="common.select">Selecionar status</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="max_clicks" class="form-label">Max Clicks</label>
<input type="number" class="form-control" id="max_clicks" name="max_clicks" min="1" placeholder="Unlimited">
<div class="form-text">Optional: Maximum number of clicks before deactivation</div>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="expires_at" class="form-label">Expira Em</label>
<input type="datetime-local" class="form-control" id="expires_at" name="expires_at">
<div class="form-text">Optional: When this redirect should expire</div>
</div>
</div>
</div>
<div class="mb-3">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="tracking_enabled" name="tracking_enabled" value="1" checked>
<label class="form-check-label" for="tracking_enabled">
Enable Tracking
</label>
</div>
<div class="form-text">Track clicks and analytics for this redirect</div>
</div>
</div>
<!-- Filters Preview -->
<div class="col-md-4">
<h5 class="mb-3">Targeting Filters</h5>
<div class="alert alert-info">
<i class="ri-information-line me-2"></i>
<strong>No filters added yet</strong><br>
<small>Add filters to target specific users based on their location, browser, device, etc.</small>
</div>
<div id="filtersContainer">
<!-- Filters will be added here dynamically -->
</div>
<button type="button" class="btn btn-outline-primary btn-sm" id="addFilterBtn">
<i class="ri-add-line me-1"></i><span data-key="redirects.filters.add">Add Filter</span>
</button>
</div>
</div>
<hr>
<div class="d-flex justify-content-end gap-2">
<a href="/redirects/redirects" class="btn btn-secondary">Cancel</a>
<button type="submit" class="btn btn-primary">
<i class="ri-save-line me-1"></i>Create Redirect
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Add Filter Modal -->
<div class="modal fade" id="addFilterModal" tabindex="-1" aria-labelledby="addFilterModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addFilterModalLabel">Add Targeting Filter</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="addFilterForm">
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="filter_type" class="form-label">Filter Type *</label>
<select class="form-select" id="filter_type" name="filter_type" required>
<option value="">Select filter type...</option>
<option value="country">Country</option>
<option value="browser">Browser</option>
<option value="device_type">Device Type</option>
<option value="os">Operating System</option>
<option value="language">Language</option>
<option value="hour">Hour of Day</option>
<option value="referer">Referer</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="filter_operator" class="form-label">Operator *</label>
<select class="form-select" id="filter_operator" name="filter_operator" required>
<option value="equals">Equals</option>
<option value="contains">Contains</option>
<option value="starts_with">Starts with</option>
<option value="ends_with">Ends with</option>
<option value="in">In list</option>
<option value="not_in">Not in list</option>
<option value="greater_than">Greater than</option>
<option value="less_than">Less than</option>
<option value="between">Between</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="filter_value" class="form-label">Value *</label>
<input type="text" class="form-control" id="filter_value" name="filter_value" required>
<div class="form-text" id="filter_value_help"></div>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="filter_value_secondary" class="form-label">Secondary Value</label>
<input type="text" class="form-control" id="filter_value_secondary" name="filter_value_secondary">
<div class="form-text">Required for "Between" operator</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="filter_priority" class="form-label">Priority</label>
<input type="number" class="form-control" id="filter_priority" name="priority" value="0" min="0">
<div class="form-text">Higher priority filters are checked first</div>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<div class="form-check form-switch mt-4">
<input class="form-check-input" type="checkbox" id="filter_active" name="is_active" value="1" checked>
<label class="form-check-label" for="filter_active">
Active
</label>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="addFilter()">Add Filter</button>
</div>
</div>
</div>
</div>
<script>
let filters = [];
// Filter type help text
const filterHelp = {
'country': 'Enter country code (e.g., PT, US, BR)',
'browser': 'Enter browser name (e.g., Chrome, Firefox, Safari)',
'device_type': 'Enter device type (desktop, mobile, tablet, bot)',
'os': 'Enter OS name (Windows, macOS, Linux, iOS, Android)',
'language': 'Enter language code (e.g., pt-PT, en-US)',
'hour': 'Enter hour (0-23)',
'referer': 'Enter domain or URL pattern'
};
document.getElementById('filter_type').addEventListener('change', function() {
const helpText = filterHelp[this.value] || '';
document.getElementById('filter_value_help').textContent = helpText;
});
function showAddFilterModal() {
if (typeof bootstrap !== 'undefined') {
const modal = new bootstrap.Modal(document.getElementById('addFilterModal'));
modal.show();
}
}
function addFilter() {
const form = document.getElementById('addFilterForm');
const formData = new FormData(form);
const filter = {
id: Date.now(), // Temporary ID
filter_type: formData.get('filter_type'),
filter_operator: formData.get('filter_operator'),
filter_value: formData.get('filter_value'),
filter_value_secondary: formData.get('filter_value_secondary'),
priority: formData.get('priority'),
is_active: formData.get('is_active') ? 1 : 0
};
if (!filter.filter_type || !filter.filter_value) {
alert('Please fill in all required fields');
return;
}
filters.push(filter);
updateFiltersPreview();
// Close modal and reset form
if (typeof bootstrap !== 'undefined') {
bootstrap.Modal.getInstance(document.getElementById('addFilterModal')).hide();
}
form.reset();
}
function removeFilter(filterId) {
filters = filters.filter(f => f.id !== filterId);
updateFiltersPreview();
}
function updateFiltersPreview() {
const container = document.getElementById('filtersList');
const list = document.getElementById('filtersPreview');
if (filters.length === 0) {
container.classList.add('d-none');
return;
}
container.classList.remove('d-none');
list.innerHTML = '';
filters.forEach(filter => {
const li = document.createElement('li');
li.className = 'mb-2 p-2 border rounded';
li.innerHTML = `
<div class="d-flex justify-content-between align-items-center">
<div>
<strong>${filter.filter_type}</strong> ${filter.filter_operator} <code>${filter.filter_value}</code>
${filter.filter_value_secondary ? ` and <code>${filter.filter_value_secondary}</code>` : ''}
</div>
<button type="button" class="btn btn-sm btn-outline-danger" onclick="removeFilter(${filter.id})">
<i class="ri-delete-bin-line"></i>
</button>
</div>
`;
list.appendChild(li);
});
}
document.getElementById('createRedirectForm').addEventListener('submit', function(e) {
e.preventDefault();
if (!this.checkValidity()) {
e.stopPropagation();
this.classList.add('was-validated');
return;
}
const formData = new FormData(this);
const data = {
name: formData.get('name'),
source_url: formData.get('source_url'),
target_url: formData.get('target_url'),
fallback_url: formData.get('fallback_url'),
redirect_type: formData.get('redirect_type'),
status: formData.get('status'),
tracking_enabled: formData.get('tracking_enabled') ? 1 : 0,
max_clicks: formData.get('max_clicks') || null,
expires_at: formData.get('expires_at') || null,
filters: filters
};
// Create redirect
fetch('/api/redirects', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
if (result.success) {
alert('Redirect created successfully!');
window.location.href = '/redirects/redirects';
} else {
alert('Error: ' + result.error);
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while creating the redirect');
});
});
</script>
+138
View File
@@ -0,0 +1,138 @@
<?php
/**
* Edit Redirect View - Alpine.js Version
*
* Loads data via API instead of PHP inline
*/
?>
<div class="row" x-data="editRedirect()" x-init="loadRedirect()">
<div class="col-12">
<div class="card">
<div class="card-body">
<!-- Loading state -->
<div x-show="loading" class="text-center py-4">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">A carregar dados do redirect...</p>
</div>
<!-- Error state -->
<div x-show="error" class="alert alert-danger" x-text="error"></div>
<!-- Form content -->
<template x-if="!loading && !error && redirect">
<form id="editRedirectForm" @submit.prevent="updateRedirect">
<input type="hidden" name="_method" value="PUT">
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="name" class="form-label">Nome do Redirect</label>
<input type="text" class="form-control" id="name" name="name" x-model="redirect.name" required>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Estado</label>
<div>
<input type="checkbox" class="btn-check" id="status-toggle" autocomplete="off" x-model="redirect.status" :true-value="1" :false-value="0">
<input type="hidden" name="status" :value="redirect.status">
<label class="btn btn-outline-success" for="status-toggle" x-show="redirect.status == 1">
<i class="ri-toggle-line me-1"></i> Ativo
</label>
<label class="btn btn-outline-secondary" for="status-toggle" x-show="redirect.status == 0">
<i class="ri-toggle-line me-1"></i> Inativo
</label>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="source_url" class="form-label">URL de Origem</label>
<input type="url" class="form-control" id="source_url" name="source_url" x-model="redirect.source_url" required>
<small class="form-text text-muted">A URL que irá ativar o redirect</small>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="target_url" class="form-label">URL de Destino</label>
<input type="url" class="form-control" id="target_url" name="target_url" x-model="redirect.target_url" required>
<small class="form-text text-muted">Para onde os utilizadores serão redirecionados quando os filtros corresponderem</small>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="fallback_url" class="form-label">URL de Fallback (Opcional)</label>
<input type="url" class="form-control" id="fallback_url" name="fallback_url" x-model="redirect.fallback_url">
<small class="form-text text-muted">Para onde os utilizadores serão redirecionados quando os filtros não corresponderem</small>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="redirect_type" class="form-label">Tipo de Redirect</label>
<select class="form-select" id="redirect_type" name="redirect_type" x-model="redirect.redirect_type">
<option value="302">302 (Temporário)</option>
<option value="301">301 (Permanente)</option>
<option value="meta">Meta Refresh</option>
<option value="javascript">JavaScript</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="max_clicks" class="form-label">Clicks Máximos (Opcional)</label>
<input type="number" class="form-control" id="max_clicks" name="max_clicks" x-model="redirect.max_clicks" min="1">
<small class="form-text text-muted">Desativar após este número de clicks</small>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="expires_at" class="form-label">Expira Em (Opcional)</label>
<input type="datetime-local" class="form-control" id="expires_at" name="expires_at" :value="formatDateForInput(redirect.expires_at)">
</div>
</div>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="tracking_enabled" name="tracking_enabled" value="1" x-model="redirect.tracking_enabled" x-show="redirect">
<label class="form-check-label" for="tracking_enabled" x-show="redirect">
Ativar rastreamento e analytics
</label>
</div>
</div>
<!-- Success message -->
<div x-show="success" class="alert alert-success alert-dismissible fade show" role="alert">
<i class="ri-check-double-line me-1 align-middle"></i>
<strong>Sucesso!</strong> Redirect atualizado com sucesso.
<button type="button" class="btn-close" @click="success = false"></button>
</div>
<div class="text-end">
<button type="button" class="btn btn-secondary me-2" @click="goBack()">Cancelar</button>
<button type="submit" class="btn btn-primary" :disabled="saving">
<span x-show="!saving">Atualizar Redirect</span>
<span x-show="saving">
<span class="spinner-border spinner-border-sm me-1" role="status"></span>
A guardar...
</span>
</button>
</div>
</form>
</template>
</div>
</div>
</div>
</div>
+152
View File
@@ -0,0 +1,152 @@
<?php
/**
* All Redirects List - Alpine.js Version
*
* Loads data via API instead of PHP inline
*/
?>
<div x-data="redirectsList()">
<!-- Loading state -->
<div x-show="loading" class="text-center py-5">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">A carregar redirects...</p>
</div>
<!-- Error state -->
<div x-show="error" class="alert alert-danger" x-text="error"></div>
<!-- Content -->
<div x-show="!loading && !error">
<!-- Filters -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<form @submit.prevent="applyFilters()" class="row g-3">
<div class="col-md-4">
<label class="form-label">Pesquisar</label>
<input type="text" class="form-control" x-model="filters.search" placeholder="Pesquisar por nome ou URL...">
</div>
<div class="col-md-3">
<label class="form-label">Estado</label>
<select class="form-select" x-model="filters.status">
<option value="">Todos os Estados</option>
<option value="1">Ativo</option>
<option value="0">Inativo</option>
</select>
</div>
<div class="col-md-3">
<label class="form-label">&nbsp;</label>
<div class="d-flex gap-2">
<button type="submit" class="btn btn-primary">
<i class="ri-search-line me-1"></i>Filtrar
</button>
<button type="button" class="btn btn-outline-secondary" @click="clearFilters()">
<i class="ri-refresh-line me-1"></i>Limpar
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Redirects List -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="d-flex align-items-center mb-4">
<h4 class="card-title mb-0">Redirects (<span x-text="redirects.length"></span>)</h4>
<div class="flex-grow-1"></div>
<button type="button" class="btn btn-primary" @click="goToCreate()">
<i class="ri-add-line me-1"></i>Criar Redirect
</button>
</div>
<!-- Empty state -->
<div x-show="redirects.length === 0" class="text-center py-5">
<i class="ri-link font-size-64 text-muted"></i>
<h4 class="mt-3 text-muted">Nenhum redirect encontrado</h4>
<p class="text-muted">Crie o seu primeiro redirect para começar</p>
<button type="button" class="btn btn-primary" @click="goToCreate()">Criar Redirect</button>
</div>
<!-- Table -->
<div x-show="redirects.length > 0" class="table-responsive">
<table class="table table-centered table-nowrap mb-0">
<thead>
<tr>
<th>Nome</th>
<th>URL de Origem</th>
<th>URL de Destino</th>
<th>Estado</th>
<th>Tipo</th>
<th>Rastreamento</th>
<th>Criado</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<template x-for="redirect in redirects" :key="redirect.id">
<tr>
<td>
<div class="d-flex align-items-center">
<div class="avatar-sm bg-light rounded-circle me-3">
<span class="avatar-title">
<i class="ri-link font-size-16"></i>
</span>
</div>
<div>
<h6 class="mb-0" x-text="redirect.name"></h6>
<small class="text-muted" x-text="redirect.id"></small>
</div>
</div>
</td>
<td>
<span class="text-truncate d-inline-block" style="max-width: 150px;" :title="redirect.source_url" x-text="redirect.source_url"></span>
</td>
<td>
<span class="text-truncate d-inline-block" style="max-width: 150px;" :title="redirect.target_url" x-text="redirect.target_url"></span>
</td>
<td>
<span class="badge" :class="getStatusBadgeClass(redirect.status)" x-text="getStatusText(redirect.status)"></span>
</td>
<td>
<span class="badge" :class="getTypeBadgeClass(redirect.redirect_type)" x-text="redirect.redirect_type"></span>
</td>
<td>
<span class="badge" :class="getTrackingBadgeClass(redirect.tracking_enabled)" x-text="getTrackingText(redirect.tracking_enabled)"></span>
</td>
<td>
<span x-text="formatDate(redirect.created_at)"></span>
</td>
<td>
<div class="dropdown">
<a href="#" class="dropdown-toggle card-drop" data-bs-toggle="dropdown" aria-expanded="false">
<i class="ri-more-fill"></i>
</a>
<ul class="dropdown-menu dropdown-menu-end">
<li><a class="dropdown-item" href="#" @click.prevent="goToView(redirect.id)"><i class="ri-eye-line me-2"></i>Ver</a></li>
<li><a class="dropdown-item" href="#" @click.prevent="goToEdit(redirect.id)"><i class="ri-pencil-line me-2"></i>Editar</a></li>
<li><a class="dropdown-item" :href="`/r/${redirect.cuid}`" target="_blank"><i class="ri-external-link-line me-2"></i>Testar</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item text-danger" href="#" @click.prevent="deleteRedirect(redirect.id, redirect.name)"><i class="ri-delete-bin-line me-2"></i>Apagar</a></li>
</ul>
</div>
</td>
</tr>
</template>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
+282
View File
@@ -0,0 +1,282 @@
<?php
/**
* View Redirect Details
*
* @var array $redirect Redirect data
* @var array $filters Filters data
* @var array $stats Statistics data
* @var array $recentActivity Recent activity data
*/
?>
<div class="row">
<div class="col-lg-8">
<!-- Redirect Details -->
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Redirect Details</h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<p><strong>Name:</strong> <?= htmlspecialchars($redirect['name']) ?></p>
<p><strong>Status:</strong>
<span class="badge bg-<?= $redirect['status'] == 1 ? 'success' : 'warning' ?>">
<?= $redirect['status'] == 1 ? 'Active' : 'Inactive' ?>
</span>
</p>
<p><strong>Redirect Type:</strong> <?= htmlspecialchars($redirect['redirect_type']) ?></p>
<p><strong>Tracking:</strong>
<span class="badge bg-<?= $redirect['tracking_enabled'] ? 'info' : 'secondary' ?>">
<?= $redirect['tracking_enabled'] ? 'Enabled' : 'Disabled' ?>
</span>
</p>
</div>
<div class="col-md-6">
<p><strong>Created:</strong> <?= date('M j, Y H:i', strtotime($redirect['created_at'])) ?></p>
<p><strong>Updated:</strong> <?= date('M j, Y H:i', strtotime($redirect['updated_at'])) ?></p>
<?php if ($redirect['expires_at']): ?>
<p><strong>Expires:</strong> <?= date('M j, Y H:i', strtotime($redirect['expires_at'])) ?></p>
<?php endif; ?>
<?php if ($redirect['max_clicks']): ?>
<p><strong>Max Clicks:</strong> <?= number_format($redirect['max_clicks']) ?></p>
<?php endif; ?>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-4">
<h6>Source URL</h6>
<p class="text-break"><?= htmlspecialchars($redirect['source_url']) ?></p>
</div>
<div class="col-md-4">
<h6>Target URL</h6>
<p class="text-break"><?= htmlspecialchars($redirect['target_url']) ?></p>
</div>
<div class="col-md-4">
<h6>Fallback URL</h6>
<p class="text-break"><?= $redirect['fallback_url'] ? htmlspecialchars($redirect['fallback_url']) : '<em>None</em>' ?></p>
</div>
</div>
<div class="mt-3">
<a href="/redirects/redirects/<?= $redirect['id'] ?>/edit" class="btn btn-primary me-2">Edit Redirect</a>
<a href="/r/<?= $redirect['cuid'] ?>" target="_blank" class="btn btn-info me-2">Test Redirect</a>
<button class="btn btn-danger" onclick="deleteRedirect(<?= $redirect['id'] ?>)">Delete</button>
</div>
</div>
</div>
<!-- Filters -->
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h4 class="card-title mb-0">Filters</h4>
<button class="btn btn-sm btn-primary" onclick="addFilter()">Add Filter</button>
</div>
<div class="card-body">
<?php if (empty($filters)): ?>
<p class="text-muted">No filters configured. All visitors will be redirected to the target URL.</p>
<?php else: ?>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Type</th>
<th>Value</th>
<th>Operator</th>
<th>Priority</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($filters as $filter): ?>
<tr>
<td><?= htmlspecialchars(ucfirst($filter['filter_type'])) ?></td>
<td><?= htmlspecialchars($filter['filter_value']) ?></td>
<td><?= htmlspecialchars(ucfirst(str_replace('_', ' ', $filter['filter_operator']))) ?></td>
<td><?= $filter['priority'] ?></td>
<td>
<span class="badge bg-<?= $filter['is_active'] ? 'success' : 'secondary' ?>">
<?= $filter['is_active'] ? 'Active' : 'Inactive' ?>
</span>
</td>
<td>
<button class="btn btn-sm btn-outline-primary" onclick="editFilter(<?= $filter['id'] ?>)">Edit</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteFilter(<?= $filter['id'] ?>)">Delete</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</div>
<div class="col-lg-4">
<!-- Statistics -->
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Statistics</h4>
</div>
<div class="card-body">
<div class="row text-center">
<div class="col-6">
<h4 class="text-primary"><?= number_format($stats['total_clicks'] ?? 0) ?></h4>
<p class="text-muted mb-0">Total Clicks</p>
</div>
<div class="col-6">
<h4 class="text-success"><?= number_format($stats['unique_clicks'] ?? 0) ?></h4>
<p class="text-muted mb-0">Unique Clicks</p>
</div>
</div>
<hr>
<div class="row text-center">
<div class="col-6">
<h4 class="text-info"><?= number_format($stats['unique_ips'] ?? 0) ?></h4>
<p class="text-muted mb-0">Unique IPs</p>
</div>
<div class="col-6">
<h4 class="text-warning"><?= number_format($stats['avg_response_time'] ?? 0, 1) ?>ms</h4>
<p class="text-muted mb-0">Avg Response</p>
</div>
</div>
</div>
</div>
<!-- Recent Activity -->
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Recent Activity</h4>
</div>
<div class="card-body">
<?php if (empty($recentActivity)): ?>
<p class="text-muted">No recent activity</p>
<?php else: ?>
<div class="timeline">
<?php foreach (array_slice($recentActivity, 0, 5) as $activity): ?>
<div class="timeline-item">
<div class="timeline-marker"></div>
<div class="timeline-content">
<h6 class="mb-1">Click from <?= htmlspecialchars($activity['ip_address']) ?></h6>
<p class="text-muted mb-1">
<?= date('M j, Y H:i', strtotime($activity['timestamp'])) ?>
<?php if ($activity['country_code']): ?>
• <?= htmlspecialchars($activity['country_code']) ?>
<?php endif; ?>
<?php if ($activity['browser']): ?>
• <?= htmlspecialchars($activity['browser']) ?>
<?php endif; ?>
</p>
<div class="small text-muted">
<?php if ($activity['device_type']): ?>
<span class="badge bg-light text-dark me-1"><?= htmlspecialchars($activity['device_type']) ?></span>
<?php endif; ?>
<?php if ($activity['city']): ?>
<span class="badge bg-light text-dark me-1"><?= htmlspecialchars($activity['city']) ?></span>
<?php endif; ?>
<?php if ($activity['target_url_used']): ?>
<div class="mt-1">
<small class="text-break">→ <?= htmlspecialchars($activity['target_url_used']) ?></small>
</div>
<?php endif; ?>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<script>
function deleteRedirect(id) {
if (confirm('Are you sure you want to delete this redirect?')) {
fetch(`/api/redirects/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
window.location.href = '/redirects/redirects';
} else {
alert('Error: ' + data.error);
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while deleting the redirect');
});
}
}
function addFilter() {
// Implement filter addition modal/form
alert('Filter addition functionality will be implemented');
}
function editFilter(filterId) {
// Implement filter editing modal/form
alert('Filter editing functionality will be implemented');
}
function deleteFilter(filterId) {
if (confirm('Are you sure you want to delete this filter?')) {
fetch(`/api/redirects/<?= $redirect['id'] ?>/filters/${filterId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
location.reload();
} else {
alert('Error: ' + data.error);
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while deleting the filter');
});
}
}
</script>
<style>
.timeline {
position: relative;
padding-left: 20px;
}
.timeline-item {
position: relative;
margin-bottom: 15px;
}
.timeline-marker {
position: absolute;
left: -20px;
top: 5px;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #007bff;
}
.timeline-content {
padding-left: 10px;
}
</style>
+308
View File
@@ -0,0 +1,308 @@
<?php
/**
* Redirects Settings View
*
* @var string $title Page title
*/
?>
<div class="row">
<div class="col-lg-8">
<!-- General Settings -->
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">General Settings</h4>
</div>
<div class="card-body">
<form id="generalSettingsForm">
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="tracking_enabled" class="form-label">Default Tracking</label>
<select class="form-select" id="tracking_enabled" name="tracking_enabled">
<option value="1">Enabled</option>
<option value="0">Disabled</option>
</select>
<small class="form-text text-muted">Enable tracking by default for new redirects</small>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="default_redirect_type" class="form-label">Default Redirect Type</label>
<select class="form-select" id="default_redirect_type" name="default_redirect_type">
<option value="302">302 (Temporary)</option>
<option value="301">301 (Permanent)</option>
<option value="meta">Meta Refresh</option>
<option value="javascript">JavaScript</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="retention_days" class="form-label">Data Retention (Days)</label>
<input type="number" class="form-control" id="retention_days" name="retention_days" value="90" min="1" max="365">
<small class="form-text text-muted">How long to keep detailed statistics</small>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="max_filters_per_redirect" class="form-label">Max Filters per Redirect</label>
<input type="number" class="form-control" id="max_filters_per_redirect" name="max_filters_per_redirect" value="10" min="1" max="50">
</div>
</div>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="aggregation_enabled" name="aggregation_enabled" value="1" checked>
<label class="form-check-label" for="aggregation_enabled">
Enable daily aggregation for better performance
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Save General Settings</button>
</form>
</div>
</div>
<!-- Security Settings -->
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Security Settings</h4>
</div>
<div class="card-body">
<form id="securitySettingsForm">
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="rate_limit_per_ip" class="form-label">Rate Limit per IP</label>
<input type="number" class="form-control" id="rate_limit_per_ip" name="rate_limit_per_ip" value="100" min="1">
<small class="form-text text-muted">Maximum clicks per IP per hour</small>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="geo_detection_method" class="form-label">Geo Detection Method</label>
<select class="form-select" id="geo_detection_method" name="geo_detection_method">
<option value="cloudflare">Cloudflare Headers</option>
<option value="ipapi">IP-API Service</option>
<option value="manual">Manual Configuration</option>
</select>
</div>
</div>
</div>
<div class="mb-3">
<label for="allowed_domains" class="form-label">Allowed Target Domains</label>
<textarea class="form-control" id="allowed_domains" name="allowed_domains" rows="3" placeholder="Enter domains, one per line (leave empty to allow all)"></textarea>
<small class="form-text text-muted">Restrict redirects to specific domains for security</small>
</div>
<div class="mb-3">
<label for="blocked_domains" class="form-label">Blocked Target Domains</label>
<textarea class="form-control" id="blocked_domains" name="blocked_domains" rows="3" placeholder="Enter domains to block, one per line"></textarea>
<small class="form-text text-muted">Prevent redirects to specific domains</small>
</div>
<button type="submit" class="btn btn-primary">Save Security Settings</button>
</form>
</div>
</div>
</div>
<div class="col-lg-4">
<!-- Module Information -->
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Module Information</h4>
</div>
<div class="card-body">
<div class="mb-3">
<strong>Version:</strong> 1.0.0
</div>
<div class="mb-3">
<strong>Author:</strong> BitReport Unip. LDA
</div>
<div class="mb-3">
<strong>Last Updated:</strong> <?= date('M j, Y') ?>
</div>
<div class="mb-3">
<strong>Status:</strong>
<span class="badge bg-success">Active</span>
</div>
</div>
</div>
<!-- Quick Actions -->
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Quick Actions</h4>
</div>
<div class="card-body">
<div class="d-grid gap-2">
<button class="btn btn-outline-primary" onclick="exportData()">
<i class="ri-download-line me-2"></i>Export Data
</button>
<button class="btn btn-outline-warning" onclick="clearOldData()">
<i class="ri-delete-bin-line me-2"></i>Clear Old Data
</button>
<button class="btn btn-outline-info" onclick="testGeoDetection()">
<i class="ri-global-line me-2"></i>Test Geo Detection
</button>
<button class="btn btn-outline-secondary" onclick="resetSettings()">
<i class="ri-refresh-line me-2"></i>Reset to Defaults
</button>
</div>
</div>
</div>
<!-- System Status -->
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">System Status</h4>
</div>
<div class="card-body">
<div class="mb-3">
<strong>Database Tables:</strong>
<span class="badge bg-success">✓ All Present</span>
</div>
<div class="mb-3">
<strong>Geo Detection:</strong>
<span class="badge bg-success">✓ Working</span>
</div>
<div class="mb-3">
<strong>Tracking:</strong>
<span class="badge bg-success">✓ Active</span>
</div>
<div class="mb-3">
<strong>Performance:</strong>
<span class="badge bg-success">✓ Optimized</span>
</div>
</div>
</div>
</div>
</div>
<script>
// Load current settings
document.addEventListener('DOMContentLoaded', function() {
loadSettings();
});
function loadSettings() {
fetch('/api/redirects/settings')
.then(response => response.json())
.then(data => {
if (data.success) {
const settings = data.settings;
// Populate form fields
document.getElementById('tracking_enabled').value = settings.tracking_enabled || '1';
document.getElementById('default_redirect_type').value = settings.default_redirect_type || '302';
document.getElementById('retention_days').value = settings.retention_days || '90';
document.getElementById('max_filters_per_redirect').value = settings.max_filters_per_redirect || '10';
document.getElementById('aggregation_enabled').checked = settings.aggregation_enabled == '1';
document.getElementById('rate_limit_per_ip').value = settings.rate_limit_per_ip || '100';
document.getElementById('geo_detection_method').value = settings.geo_detection_method || 'cloudflare';
// Parse JSON arrays
if (settings.allowed_domains) {
try {
const domains = JSON.parse(settings.allowed_domains);
document.getElementById('allowed_domains').value = domains.join('\n');
} catch (e) {
document.getElementById('allowed_domains').value = '';
}
}
if (settings.blocked_domains) {
try {
const domains = JSON.parse(settings.blocked_domains);
document.getElementById('blocked_domains').value = domains.join('\n');
} catch (e) {
document.getElementById('blocked_domains').value = '';
}
}
}
})
.catch(error => {
console.error('Error loading settings:', error);
});
}
// Save general settings
document.getElementById('generalSettingsForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const data = Object.fromEntries(formData.entries());
saveSettings(data, 'General settings saved successfully!');
});
// Save security settings
document.getElementById('securitySettingsForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const data = Object.fromEntries(formData.entries());
// Convert domain lists to JSON
if (data.allowed_domains) {
data.allowed_domains = JSON.stringify(data.allowed_domains.split('\n').filter(d => d.trim()));
}
if (data.blocked_domains) {
data.blocked_domains = JSON.stringify(data.blocked_domains.split('\n').filter(d => d.trim()));
}
saveSettings(data, 'Security settings saved successfully!');
});
function saveSettings(data, message) {
fetch('/api/redirects/settings', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
if (result.success) {
alert(message);
} else {
alert('Error: ' + result.error);
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while saving settings');
});
}
function exportData() {
alert('Export functionality will be implemented');
}
function clearOldData() {
if (confirm('Are you sure you want to clear old data? This action cannot be undone.')) {
alert('Data clearing functionality will be implemented');
}
}
function testGeoDetection() {
alert('Geo detection test functionality will be implemented');
}
function resetSettings() {
if (confirm('Are you sure you want to reset all settings to defaults?')) {
alert('Settings reset functionality will be implemented');
}
}
</script>
+441
View File
@@ -0,0 +1,441 @@
<?php
/**
* Redirects Analytics View
*
* @var array $stats Statistics data
* @var string $startDate Start date for filtering
* @var string $endDate End date for filtering
*/
?>
<div x-data="redirectsStats()" x-init="init()">
<!-- Filters -->
<div class="row">
<div class="col-12">
<div class="card border-0 shadow-sm">
<div class="card-header bg-transparent border-0 pb-0">
<h5 class="card-title mb-0">
<i class="ri-filter-3-line me-2 text-primary"></i>
<span>Filtros Avançados</span>
</h5>
</div>
<div class="card-body pt-3">
<div class="row g-3">
<!-- Date Range Filter -->
<div class="col-lg-3 col-md-6">
<label class="form-label fw-semibold text-dark">
<i class="ri-calendar-line me-1"></i>
<span>Intervalo de Datas</span>
</label>
<select class="form-select border-0 bg-light" x-model="selectedRange" @change="updateDateRange()">
<option value="all">Todo o Tempo</option>
<option value="7">Últimos 7 Dias</option>
<option value="30">Últimos 30 Dias</option>
<option value="90">Últimos 90 Dias</option>
<option value="month">Este Mês</option>
<option value="year">Este Ano</option>
<option value="custom">Intervalo Personalizado</option>
</select>
</div>
<!-- Tracker/Redirect Filter -->
<div class="col-lg-3 col-md-6">
<label class="form-label fw-semibold text-dark">
<i class="ri-link me-1"></i>
<span>Tracker</span>
</label>
<select class="form-select border-0 bg-light" x-model="selectedTracker">
<option value="">All Trackers</option>
<template x-for="redirect in availableRedirects" :key="redirect.id">
<option :value="redirect.id" x-text="redirect.name + ' (' + redirect.id + ')'"></option>
</template>
</select>
</div>
<!-- Country Filter -->
<div class="col-lg-3 col-md-6">
<label class="form-label fw-semibold text-dark">
<i class="ri-global-line me-1"></i>
<span>País</span>
</label>
<select class="form-select border-0 bg-light" x-model="selectedCountry">
<option value="">All Countries</option>
<template x-for="country in availableCountries" :key="country.country_code">
<option :value="country.country_code" x-text="country.country_name + ' (' + country.country_code + ')'"></option>
</template>
</select>
</div>
<!-- Device Filter -->
<div class="col-lg-3 col-md-6">
<label class="form-label fw-semibold text-dark">
<i class="ri-smartphone-line me-1"></i>
<span>Dispositivo</span>
</label>
<select class="form-select border-0 bg-light" x-model="selectedDevice">
<option value="">All Devices</option>
<option value="desktop">Desktop</option>
<option value="mobile">Mobile</option>
<option value="tablet">Tablet</option>
<option value="bot">Bot</option>
</select>
</div>
<!-- Browser Filter -->
<div class="col-lg-3 col-md-6">
<label class="form-label fw-semibold text-dark">
<i class="ri-window-line me-1"></i>
<span>Navegador</span>
</label>
<select class="form-select border-0 bg-light" x-model="selectedBrowser">
<option value="">All Browsers</option>
<template x-for="browser in availableBrowsers" :key="browser.browser">
<option :value="browser.browser" x-text="browser.browser"></option>
</template>
</select>
</div>
<!-- Operating System Filter -->
<div class="col-lg-3 col-md-6">
<label class="form-label fw-semibold text-dark">
<i class="ri-computer-line me-1"></i>
<span>Sistema Operativo</span>
</label>
<select class="form-select border-0 bg-light" x-model="selectedOS">
<option value="">All Operating Systems</option>
<template x-for="os in availableOS" :key="os.os">
<option :value="os.os" x-text="os.os"></option>
</template>
</select>
</div>
<!-- Custom Date Inputs -->
<div class="col-lg-3 col-md-6" x-show="selectedRange === 'custom'">
<label class="form-label fw-semibold text-dark">
<i class="ri-calendar-event-line me-1"></i>
<span>Data Início</span>
</label>
<input type="date" class="form-control border-0 bg-light" x-model="startDate">
</div>
<div class="col-lg-3 col-md-6" x-show="selectedRange === 'custom'">
<label class="form-label fw-semibold text-dark">
<i class="ri-calendar-event-line me-1"></i>
<span>Data Fim</span>
</label>
<input type="date" class="form-control border-0 bg-light" x-model="endDate">
</div>
<!-- Action Buttons -->
<div class="col-12">
<div class="d-flex gap-2 justify-content-center">
<button type="button" class="btn btn-primary px-4" @click="loadStats()" :disabled="loading">
<span x-show="loading" class="spinner-border spinner-border-sm me-2"></span>
<i class="ri-search-line me-1"></i>
<span>Filtrar</span>
</button>
<button type="button" class="btn btn-outline-secondary px-4" @click="resetFilters()">
<i class="ri-refresh-line me-1"></i>
<span>Reset</span>
</button>
<button type="button" class="btn btn-outline-info px-4" @click="exportStats()">
<i class="ri-download-line me-1"></i>
<span>Exportar</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Overview Stats -->
<div class="row">
<div class="col-xl-3 col-md-6">
<div class="card border-0 shadow-sm stats-card">
<div class="card-body">
<div class="d-flex align-items-center">
<div class="avatar-sm bg-primary-subtle rounded-circle me-3 stats-icon">
<i class="ri-mouse-line text-primary font-size-18"></i>
</div>
<div class="flex-grow-1">
<p class="text-muted mb-1">Total de Cliques</p>
<h3 class="mb-0" x-text="formatNumber(stats.overview.total_clicks)">0</h3>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-6">
<div class="card border-0 shadow-sm stats-card">
<div class="card-body">
<div class="d-flex align-items-center">
<div class="avatar-sm bg-success-subtle rounded-circle me-3 stats-icon">
<i class="ri-user-line text-success font-size-18"></i>
</div>
<div class="flex-grow-1">
<p class="text-muted mb-1">Cliques Únicos</p>
<h3 class="mb-0" x-text="formatNumber(stats.overview.unique_clicks)">0</h3>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-6">
<div class="card border-0 shadow-sm stats-card">
<div class="card-body">
<div class="d-flex align-items-center">
<div class="avatar-sm bg-info-subtle rounded-circle me-3 stats-icon">
<i class="ri-global-line text-info font-size-18"></i>
</div>
<div class="flex-grow-1">
<p class="text-muted mb-1">IPs Únicos</p>
<h3 class="mb-0" x-text="formatNumber(stats.overview.unique_ips)">0</h3>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-6">
<div class="card border-0 shadow-sm stats-card">
<div class="card-body">
<div class="d-flex align-items-center">
<div class="avatar-sm bg-warning-subtle rounded-circle me-3 stats-icon">
<i class="ri-time-line text-warning font-size-18"></i>
</div>
<div class="flex-grow-1">
<p class="text-muted mb-1">Tempo Médio de Resposta</p>
<h3 class="mb-0"><span x-text="formatNumber(stats.overview.avg_response_time, 2)">0</span>ms</h3>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Charts Row -->
<div class="row">
<div class="col-lg-4">
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Cliques por País</h4>
</div>
<div class="card-body">
<div style="height: 300px;">
<canvas id="country-chart"></canvas>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Cliques por Dispositivo</h4>
</div>
<div class="card-body">
<div style="height: 300px;">
<canvas id="device-chart"></canvas>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Cliques por Navegador</h4>
</div>
<div class="card-body">
<div style="height: 300px;">
<canvas id="browser-chart"></canvas>
</div>
</div>
</div>
</div>
</div>
<!-- Detailed Tables -->
<div class="row">
<!-- Top Countries Table -->
<div class="col-lg-6">
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Top Países</h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered mb-0">
<thead>
<tr>
<th>País</th>
<th>Cliques</th>
<th>Percentagem</th>
</tr>
</thead>
<tbody>
<template x-for="country in stats.by_country" :key="country.country_code">
<tr>
<td x-text="country.country_code"></td>
<td x-text="formatNumber(country.clicks)"></td>
<td>
<span x-text="formatNumber(calculatePercentage(country.clicks, stats.overview.total_clicks), 1) + '%'"></span>
</td>
</tr>
</template>
<tr x-show="stats.by_country.length === 0">
<td colspan="3" class="text-center text-muted">Nenhum dado disponível</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Top Devices Table -->
<div class="col-lg-6">
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Top Dispositivos</h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered mb-0">
<thead>
<tr>
<th>Dispositivo</th>
<th>Cliques</th>
<th>Percentagem</th>
</tr>
</thead>
<tbody>
<template x-for="device in stats.by_device" :key="device.device_type">
<tr>
<td x-text="device.device_type"></td>
<td x-text="formatNumber(device.clicks)"></td>
<td>
<span x-text="formatNumber(calculatePercentage(device.clicks, stats.overview.total_clicks), 1) + '%'"></span>
</td>
</tr>
</template>
<tr x-show="stats.by_device.length === 0">
<td colspan="3" class="text-center text-muted">Nenhum dado disponível</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Data for JavaScript -->
<script>
window.redirectsStatsData = {
startDate: '<?= $startDate ?>',
endDate: '<?= $endDate ?>',
filterOptions: {
redirects: <?= json_encode($filterOptions['redirects'] ?? []) ?>,
countries: <?= json_encode($filterOptions['countries'] ?? []) ?>,
browsers: <?= json_encode($filterOptions['browsers'] ?? []) ?>,
operatingSystems: <?= json_encode($filterOptions['operatingSystems'] ?? []) ?>
},
stats: {
overview: <?= json_encode($stats['overview'] ?? []) ?>,
by_country: <?= json_encode($stats['by_country'] ?? []) ?>,
by_device: <?= json_encode($stats['by_device'] ?? []) ?>,
by_browser: <?= json_encode($stats['by_browser'] ?? []) ?>
}
};
</script>
<style>
.stats-card {
transition: all 0.3s ease;
border-radius: 12px;
}
.stats-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(0,0,0,0.1) !important;
}
.stats-icon {
width: 60px;
height: 60px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
}
.stats-card:hover .stats-icon {
transform: scale(1.1);
}
.form-select.border-0,
.form-control.border-0 {
background-color: #f8f9fa !important;
border-radius: 8px;
padding: 0.75rem 1rem;
transition: all 0.2s ease;
}
.form-select.border-0:focus,
.form-control.border-0:focus {
background-color: #ffffff !important;
box-shadow: 0 0 0 0.2rem rgba(85, 110, 230, 0.25);
border-color: #556ee6;
}
.btn {
border-radius: 8px;
font-weight: 500;
transition: all 0.2s ease;
}
.btn:hover {
transform: translateY(-1px);
}
.card {
border-radius: 12px;
transition: all 0.3s ease;
}
.card:hover {
box-shadow: 0 4px 20px rgba(0,0,0,0.08);
}
.card-header {
border-bottom: 1px solid rgba(0,0,0,0.05);
background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
}
.card-title {
font-weight: 600;
color: #495057;
}
.form-label {
font-weight: 600;
color: #495057;
margin-bottom: 0.5rem;
}
@media (max-width: 768px) {
.page-title-box {
flex-direction: column;
align-items: flex-start !important;
gap: 1rem;
}
.page-title-right {
width: 100%;
}
.breadcrumb {
margin: 0 !important;
}
}
</style>
+92
View File
@@ -0,0 +1,92 @@
<?php
return [
'redirect' => [
'default_status' => 'active',
'statuses' => ['active', 'inactive', 'deleted'],
'types' => ['301', '302', 'meta', 'javascript'],
'targeting_options' => [
'geo' => true,
'device' => true,
'browser' => true,
'time' => true,
'referer' => true
]
],
'tracking' => [
'enabled' => true,
'retention_days' => 90,
'aggregation_enabled' => true,
'max_filters_per_redirect' => 10
],
'filters' => [
'types' => [
'browser' => [
'label' => 'Browser',
'operators' => ['equals', 'contains', 'in', 'not_in'],
'values' => ['Chrome', 'Firefox', 'Safari', 'Edge', 'Opera', 'IE']
],
'os' => [
'label' => 'Operating System',
'operators' => ['equals', 'contains', 'in', 'not_in'],
'values' => ['Windows', 'macOS', 'Linux', 'iOS', 'Android']
],
'device_type' => [
'label' => 'Device Type',
'operators' => ['equals', 'in', 'not_in'],
'values' => ['desktop', 'mobile', 'tablet', 'bot']
],
'country' => [
'label' => 'Country',
'operators' => ['equals', 'in', 'not_in'],
'values' => ['PT', 'US', 'BR', 'ES', 'FR', 'DE', 'IT', 'NL', 'BE', 'CH']
],
'city' => [
'label' => 'City',
'operators' => ['equals', 'contains', 'starts_with', 'ends_with']
],
'region' => [
'label' => 'Region',
'operators' => ['equals', 'contains', 'starts_with', 'ends_with']
],
'timezone' => [
'label' => 'Timezone',
'operators' => ['equals', 'contains', 'in', 'not_in'],
'values' => ['Europe/Lisbon', 'America/New_York', 'America/Sao_Paulo', 'Europe/London']
],
'language' => [
'label' => 'Language',
'operators' => ['equals', 'starts_with', 'in', 'not_in'],
'values' => ['pt-PT', 'en-US', 'es-ES', 'fr-FR', 'de-DE', 'it-IT']
],
'referer' => [
'label' => 'Referer',
'operators' => ['contains', 'starts_with', 'ends_with', 'regex']
],
'hour' => [
'label' => 'Hour of Day',
'operators' => ['equals', 'greater_than', 'less_than', 'between'],
'values' => range(0, 23)
],
'asn' => [
'label' => 'ASN',
'operators' => ['equals', 'contains', 'in', 'not_in']
],
'isp' => [
'label' => 'ISP',
'operators' => ['equals', 'contains', 'starts_with', 'ends_with']
]
]
],
'performance' => [
'rate_limit_per_ip' => 100,
'cache_enabled' => true,
'cache_ttl' => 300, // 5 minutes
'max_response_time' => 1000 // 1 second
],
'security' => [
'allowed_domains' => [],
'blocked_domains' => [],
'validate_urls' => true,
'sanitize_inputs' => true
]
];
+62
View File
@@ -0,0 +1,62 @@
<?php
use App\Core\MenuManager;
// Menu principal do Redirects
MenuManager::registerMenu('Redirects', [
'id' => 11,
'label' => 'Redirects',
'icon' => 'ri-link',
'url' => '/redirects',
'order' => 4,
'parent_id' => null,
'dev' => 0,
]);
// Submenus do Redirects
MenuManager::registerMenus('Redirects', [
[
'id' => 1101,
'label' => 'Dashboard',
'icon' => 'ri-dashboard-line',
'url' => '/redirects',
'order' => 1,
'parent_id' => 11,
'dev' => 0,
],
[
'id' => 1102,
'label' => 'All Redirects',
'icon' => 'ri-list-check',
'url' => '/redirects/redirects',
'order' => 2,
'parent_id' => 11,
'dev' => 0,
],
[
'id' => 1103,
'label' => 'Create Redirect',
'icon' => 'ri-add-line',
'url' => '/redirects/redirects/create',
'order' => 3,
'parent_id' => 11,
'dev' => 0,
],
[
'id' => 1104,
'label' => 'Analytics',
'icon' => 'ri-bar-chart-line',
'url' => '/redirects/stats',
'order' => 4,
'parent_id' => 11,
'dev' => 0,
],
[
'id' => 1105,
'label' => 'Settings',
'icon' => 'ri-settings-3-line',
'url' => '/redirects/settings',
'order' => 5,
'parent_id' => 11,
'dev' => 0,
],
]);
+161
View File
@@ -0,0 +1,161 @@
<?php
/**
* BitReport CRM - Sistema de Rotas Global
*
* ⚠️ ATENÇÃO: Este ficheiro serve apenas para rotas de SISTEMA.
*
* - Rotas de funcionalidades (dashboards, apps, páginas, APIs de negócio, etc.) DEVEM ser definidas nos respetivos módulos em Modules/<Modulo>/Routes/web.php
* - Só devem existir aqui rotas de sistema, healthcheck, ferramentas internas ou fallback 404.
* - Qualquer exceção deve ser justificada e documentada.
*
* Exemplo de rotas permitidas aqui:
* - Carregamento automático dos módulos
* - Rota de healthcheck
* - Fallback 404
* - Ferramentas administrativas globais
*/
declare(strict_types=1);
use App\Core\Router;
use App\Core\View;
// --- Module Loader ---
$modulesDir = __DIR__ . '/../Modules';
$moduleFolders = scandir($modulesDir);
foreach ($moduleFolders as $moduleName) {
if ($moduleName[0] === '.') continue;
$modulePath = $modulesDir . '/' . $moduleName;
if (is_dir($modulePath)) {
// Register views namespace
if (is_dir($viewPath = $modulePath . '/Views')) {
View::addNamespace(strtolower($moduleName), $viewPath);
}
// Load routes
if (file_exists($routesPath = $modulePath . '/Routes/web.php')) {
require_once $routesPath;
}
if (file_exists($apiRoutesPath = $modulePath . '/Routes/api.php')) {
require_once $apiRoutesPath;
}
if (file_exists($publicRoutesPath = $modulePath . '/Routes/public.php')) {
require_once $publicRoutesPath;
}
// Auto-register module widgets if widgets.php exists
// TEMPORARILY DISABLED - causing memory issues
// if (file_exists($widgetsPath = $modulePath . '/widgets.php')) {
// require_once $widgetsPath;
// }
}
}
$router = Router::getInstance();
// --- SCANNER REDIRECTS ---
// Legacy redirects for scanner compatibility
// Forms redirects - redirect to correct Forms module routes
$router->get('/forms/lead', function() {
header('Location: /forms/lead', true, 302);
exit;
});
$router->get('/forms/lead/create', function() {
header('Location: /forms/lead/create', true, 302);
exit;
});
$router->get('/forms/lead/submit', function() {
header('Location: /forms/lead/submit', true, 302);
exit;
});
$router->get('/forms/lead/validate', function() {
header('Location: /forms/lead/validate', true, 302);
exit;
});
$router->get('/forms/contact', function() {
header('Location: /forms/contact', true, 302);
exit;
});
$router->get('/forms/contact/create', function() {
header('Location: /forms/contact/create', true, 302);
exit;
});
$router->get('/forms/contact/submit', function() {
header('Location: /forms/contact/submit', true, 302);
exit;
});
$router->get('/forms/contact/validate', function() {
header('Location: /forms/contact/validate', true, 302);
exit;
});
// Reports redirects - redirect to CRM reports
$router->get('/reports/sales', function() {
header('Location: /apps/crm/reports', true, 302);
exit;
});
$router->get('/reports/sales/generate', function() {
header('Location: /apps/crm/reports/deals', true, 302);
exit;
});
$router->get('/reports/sales/schedule', function() {
header('Location: /apps/crm/reports', true, 302);
exit;
});
$router->get('/reports/sales/history', function() {
header('Location: /apps/crm/reports', true, 302);
exit;
});
// System status redirects
$router->get('/system/status', function() {
header('Content-Type: application/json');
echo json_encode(['status' => 'OK', 'timestamp' => date('c')]);
exit;
});
// --- Catch-all 404 Route ---
$router->get('/{path}', function (
$path
) {
http_response_code(404);
View::render('@pages/404', [
'title' => '404 Error - Page not found',
'page_content' => function() use ($path) {
View::render('components/404.php', ['page' => $path]);
}
]);
});
// --- Dashboard API Routes ---
$router->get('/api/dashboard/stats', [App\Api\DashboardController::class, 'stats']);
$router->get('/api/dashboard/available-widgets', [App\Api\DashboardController::class, 'getAvailableWidgets']);
$router->get('/api/dashboard/user-widgets', [App\Api\DashboardController::class, 'getUserWidgets']);
$router->post('/api/dashboard/add-widget', [App\Api\DashboardController::class, 'addWidget']);
$router->post('/api/dashboard/remove-widget', [App\Api\DashboardController::class, 'removeWidget']);
$router->post('/api/dashboard/update-widget-order', [App\Api\DashboardController::class, 'updateWidgetOrder']);
$router->post('/api/dashboard/update-widget-config', [App\Api\DashboardController::class, 'updateWidgetConfig']);
// --- Log Processor API Routes ---
$router->post('/api/log-processor/process-logs', [App\Api\LogProcessorController::class, 'processLogs']);
$router->post('/api/log-processor/process-file', [App\Api\LogProcessorController::class, 'processFile']);
$router->get('/api/log-processor/stats', [App\Api\LogProcessorController::class, 'getStats']);
// --- Ferramentas internas ---
$router->get('/tools/mb-search', function() {
require __DIR__ . '/../Views/pages/public/mb-search.php';
});
+8
View File
@@ -0,0 +1,8 @@
@charset "UTF-8";@import url(https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap);@import url(https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap);@font-face{font-family:hkgrotesk;src:url(../fonts/hkgrotesk-light.eot);src:local("hkgrotesk light"),url(../fonts/hkgrotesk-light.woff) format("woff");font-weight:300}@font-face{font-family:hkgrotesk;src:url(../fonts/hkgrotesk-regular.eot);src:local("hkgrotesk regular"),url(../fonts/hkgrotesk-regular.woff) format("woff");font-weight:400}@font-face{font-family:hkgrotesk;src:url(../fonts/hkgrotesk-medium.eot);src:local("hkgrotesk medium"),url(../fonts/hkgrotesk-medium.woff) format("woff");font-weight:500}@font-face{font-family:hkgrotesk;src:url(../fonts/hkgrotesk-semibold.eot);src:local("hkgrotesk semibold"),url(../fonts/hkgrotesk-semibold.woff) format("woff");font-weight:600}@font-face{font-family:hkgrotesk;src:url(../fonts/hkgrotesk-bold.eot);src:local("hkgrotesk bold"),url(../fonts/hkgrotesk-bold.woff) format("woff");font-weight:700}#page-topbar{position:fixed;top:0;left:0;right:0;z-index:1002;background-color:var(--vz-header-bg);-webkit-transition:all .1s ease-out;transition:all .1s ease-out;border-bottom:1px solid var(--vz-header-border)}#page-topbar.topbar-shadow{-webkit-box-shadow:0 1px 2px rgba(56,65,74,.15);box-shadow:0 1px 2px rgba(56,65,74,.15)}@media (min-width:768px){#page-topbar{right:var(--vz-vertical-menu-width)}}.navbar-header{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;-webkit-box-pack:justify;justify-content:space-between;-webkit-box-align:center;-ms-flex-align:center;align-items:center;margin:0 auto;height:70px;padding:0 calc(1.5rem * .5) 0 1.5rem}@media (max-width:767.98px){.navbar-header{padding:0 calc(1.5rem * .5) 0 calc(1.5rem * .5)}}.navbar-header .topbar-head-dropdown .dropdown-menu.show{top:13px!important}.navbar-header .topbar-head-dropdown .notification-actions{display:none;position:absolute;background-color:var(--vz-secondary-bg);right:0;left:0;bottom:0;padding:7px;border-top:1px solid var(--vz-border-color)}.navbar-header .btn-topbar{height:42px;width:42px;color:var(--vz-header-item-sub-color);-webkit-transition:all .5s ease;transition:all .5s ease}.navbar-header .btn-topbar.active,.navbar-header .btn-topbar:active,.navbar-header .btn-topbar:focus,.navbar-header .btn-topbar:hover{background-color:var(--vz-header-item-bg)}@media (max-width:360px){.navbar-header .btn-topbar{height:36px;width:36px}}.navbar-header .user-name-sub-text{color:var(--vz-header-item-sub-color)}.navbar-header .user-name-text{color:var(--vz-header-item-color)}.app-search{padding:calc(32px * .5) 0}.app-search .form-control{border:none;height:38px;padding-right:40px;padding-left:30px;background-color:var(--vz-topbar-search-bg);color:var(--vz-topbar-search-color);-webkit-box-shadow:none;box-shadow:none}.app-search span.search-widget-icon{position:absolute;z-index:10;font-size:18px;line-height:38px;right:13px;top:0;color:var(--vz-header-item-sub-color)}.app-search .search-widget-icon-close{left:7px;right:auto!important}@media (max-width:1023.99px){.app-search{padding-right:calc(1.5rem * .5)}}.app-search ::-webkit-input-placeholder{color:var(--vz-header-item-sub-color)}.app-search :-ms-input-placeholder{color:var(--vz-header-item-sub-color)}.app-search ::-moz-placeholder{color:var(--vz-header-item-sub-color)}.app-search ::-ms-input-placeholder{color:var(--vz-header-item-sub-color)}.app-search ::placeholder{color:var(--vz-header-item-sub-color)}.megamenu-list li{position:relative;padding:5px 0}.megamenu-list li a{color:var(--vz-body-color)}@media (max-width:767.98px){.logo span.logo-lg{display:none}.logo span.logo-sm{display:inline-block}}.header-item{height:70px;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.header-profile-user{height:32px;width:32px}.topbar-badge-sm{left:0;top:7px!important}.topbar-badge{left:-9px;top:4px!important}@media (min-width:768px){.topbar-user{background-color:var(--vz-topbar-user-bg)}}.topbar-user .dropdown-menu{top:6px!important}.notification-item{padding:.75rem 1rem;white-space:inherit;position:relative}.notification-item .form-check-input{position:relative;z-index:2}.dropdown-icon-item{display:block;border-radius:3px;line-height:34px;text-align:center;padding:15px 0 9px;border:1px solid transparent;color:var(--vz-dropdown-link-color)}.dropdown-icon-item img{height:24px}.dropdown-icon-item span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dropdown-icon-item:hover{background-color:var(--vz-dropdown-link-hover-bg)}.fullscreen-enable [data-toggle=fullscreen] .bx-fullscreen::before{content:"\eacb"}[data-bs-theme=dark] .light-dark-mode .bx-moon::before{content:"\ec34"}[data-topbar=dark] .logo-dark{display:none}[data-topbar=dark] .logo-light{display:inline-block}[data-bs-theme=dark][data-topbar=light] .logo-dark{display:none}[data-bs-theme=Line truncated
* Waves v0.7.6
* http://fian.my.id/Waves
*
* Copyright 2014-2018 Alfiana E. Sibuea and other contributors
* Released under the MIT license
* https://github.com/fians/Waves/blob/master/LICENSE */.waves-effect{position:relative;cursor:pointer;display:inline-block;overflow:hidden;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}.waves-effect .waves-ripple{position:absolute;border-radius:50%;width:100px;height:100px;margin-top:-50px;margin-right:-50px;opacity:0;background:rgba(0,0,0,.2);background:radial-gradient(rgba(0,0,0,.2) 0,rgba(0,0,0,.3) 40%,rgba(0,0,0,.4) 50%,rgba(0,0,0,.5) 60%,rgba(255,255,255,0) 70%);-webkit-transition:all .5s ease-out;transition:all .5s ease-out;-webkit-transition-property:-webkit-transform,opacity;-webkit-transition-property:opacity,-webkit-transform;transition-property:opacity,-webkit-transform;transition-property:transform,opacity;transition-property:transform,opacity,-webkit-transform;-webkit-transform:scale(0) translate(0,0);transform:scale(0) translate(0,0);pointer-events:none}.waves-effect.waves-light .waves-ripple{background:rgba(255,255,255,.4);background:radial-gradient(rgba(255,255,255,.2) 0,rgba(255,255,255,.3) 40%,rgba(255,255,255,.4) 50%,rgba(255,255,255,.5) 60%,rgba(255,255,255,0) 70%)}.waves-effect.waves-classic .waves-ripple{background:rgba(0,0,0,.2)}.waves-effect.waves-classic.waves-light .waves-ripple{background:rgba(255,255,255,.4)}.waves-notransition{-webkit-transition:none!important;transition:none!important}.waves-button,.waves-circle{-webkit-transform:translateZ(0);transform:translateZ(0);-webkit-mask-image:-webkit-radial-gradient(circle,#fff 100%,#000 100%)}.waves-button,.waves-button-input,.waves-button:hover,.waves-button:visited{white-space:nowrap;vertical-align:middle;cursor:pointer;border:none;outline:0;color:inherit;background-color:rgba(0,0,0,0);font-size:1em;line-height:1em;text-align:center;text-decoration:none;z-index:1}.waves-button{padding:.85em 1.1em;border-radius:.2em}.waves-button-input{margin:0;padding:.85em 1.1em}.waves-input-wrapper{border-radius:.2em;vertical-align:bottom}.waves-input-wrapper.waves-button{padding:0}.waves-input-wrapper .waves-button-input{position:relative;top:0;right:0;z-index:1}.waves-circle{text-align:center;width:2.5em;height:2.5em;line-height:2.5em;border-radius:50%}.waves-float{-webkit-mask-image:none;-webkit-box-shadow:0 1px 1.5px 1px rgba(0,0,0,.12);box-shadow:0 1px 1.5px 1px rgba(0,0,0,.12);-webkit-transition:all .3s;transition:all .3s}.waves-float:active{-webkit-box-shadow:0 8px 20px 1px rgba(0,0,0,.3);box-shadow:0 8px 20px 1px rgba(0,0,0,.3)}.waves-block{display:block}.waves-effect.waves-light .waves-ripple{background-color:rgba(255,255,255,.4)}.waves-effect.waves-primary .waves-ripple{background-color:rgba(94,163,203,.4)}.waves-effect.waves-success .waves-ripple{background-color:rgba(106,218,125,.4)}.waves-effect.waves-info .waves-ripple{background-color:rgba(88,202,234,.4)}.waves-effect.waves-warning .waves-ripple{background-color:rgba(247,184,75,.4)}.waves-effect.waves-danger .waves-ripple{background-color:rgba(250,137,107,.4)}.avatar-xxs{height:1.5rem;width:1.5rem}.avatar-xs{height:2rem;width:2rem}.avatar-sm{height:3rem;width:3rem}.avatar-md{height:4.5rem;width:4.5rem}.avatar-lg{height:6rem;width:6rem}.avatar-xl{height:7.5rem;width:7.5rem}.avatar-title{-webkit-box-align:center;-ms-flex-align:center;align-items:center;background-color:#5ea3cb;color:#fff;display:-webkit-box;display:-ms-flexbox;display:flex;font-weight:500;height:100%;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;width:100%}.avatar-group{padding-right:12px;display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap}.avatar-group .avatar-group-item{margin-right:-12px;border:2px solid var(--vz-secondary-bg);border-radius:50%;-webkit-transition:all .2s;transition:all .2s}.avatar-group .avatar-group-item:hover{position:relative;-webkit-transform:translateY(-2px);transform:translateY(-2px);z-index:1}.accordion .accordion-button{font-weight:500}.accordion .accordion-body{color:var(--vz-secondary-color)}.accordion.accordion-icon-none .accordion-button::after{content:"";background-image:none!important}.accordion.accordion-icon-none .accordion-button:not(.collapsed)::after{content:""}.custom-accordionwithicon .accordion-button::after{background-image:none!important;font-family:"Material Design Icons";content:"\f0142";font-size:1.1rem;vertical-align:middle;line-height:.8}.custom-accordionwithicon .accordion-button:not(.collapsed)::after{background-image:none!important;content:"\f0140";margin-left:-3px}.custom-accordionwithicon-plus .accordion-button::after{background-image:none!important;font-family:"Material Design Icons";content:"\f0415";font-size:1.1rem;vertical-align:middle;line-height:.8}.custom-accordionwithicon-plus .accordion-button:not(.collapsed)::after{background-image:none!important;content:"\f0374";margin-left:-3px}.lefticon-accordion .accordion-button{padding-right:2.75rem}.lefticon-accordion .accordion-button::after{position:absolute;right:1.25rem;top:Line truncated
/*# sourceMappingURL=app-rtl.min.css.map */
+6
View File
@@ -0,0 +1,6 @@
@charset "UTF-8";@import url(https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap);/*!
* Bootstrap v5.3.2 (https://getbootstrap.com/)
* Copyright 2011-2023 The Bootstrap Authors
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/:root,[data-bs-theme=light]{--vz-blue:#5ea3cb;--vz-indigo:#405189;--vz-purple:#7084c7;--vz-pink:#f672a7;--vz-red:#fa896b;--vz-orange:#f1963b;--vz-yellow:#f7b84b;--vz-green:#6ada7d;--vz-teal:#02a8b5;--vz-cyan:#58caea;--vz-white:#fff;--vz-gray:#878a99;--vz-gray-dark:#343a40;--vz-gray-100:#f3f6f9;--vz-gray-200:#eff2f7;--vz-gray-300:#e9ebec;--vz-gray-400:#ced4da;--vz-gray-500:#adb5bd;--vz-gray-600:#878a99;--vz-gray-700:#495057;--vz-gray-800:#343a40;--vz-gray-900:#212529;--vz-primary:#5ea3cb;--vz-secondary:#7084c7;--vz-success:#6ada7d;--vz-info:#58caea;--vz-warning:#f7b84b;--vz-danger:#fa896b;--vz-light:#f3f6f9;--vz-dark:#212529;--vz-primary-rgb:94,163,203;--vz-secondary-rgb:112,132,199;--vz-success-rgb:106,218,125;--vz-info-rgb:88,202,234;--vz-warning-rgb:247,184,75;--vz-danger-rgb:250,137,107;--vz-light-rgb:243,246,249;--vz-dark-rgb:33,37,41;--vz-primary-text-emphasis:#508bad;--vz-secondary-text-emphasis:#5f70a9;--vz-success-text-emphasis:#5ab96a;--vz-info-text-emphasis:#4bacc7;--vz-warning-text-emphasis:#d29c40;--vz-danger-text-emphasis:#d5745b;--vz-light-text-emphasis:#ced4da;--vz-dark-text-emphasis:#343a40;--vz-primary-bg-subtle:#e7f1f7;--vz-secondary-bg-subtle:#eaedf7;--vz-success-bg-subtle:#e9f9ec;--vz-info-bg-subtle:#e6f7fc;--vz-warning-bg-subtle:#fef4e4;--vz-danger-bg-subtle:#feede9;--vz-light-bg-subtle:#f9fbfc;--vz-dark-bg-subtle:#e9ebec;--vz-primary-border-subtle:#bfdaea;--vz-secondary-border-subtle:#c6cee9;--vz-success-border-subtle:#c3f0cb;--vz-info-border-subtle:#bceaf7;--vz-warning-border-subtle:#fce3b7;--vz-danger-border-subtle:#fdd0c4;--vz-light-border-subtle:#eff2f7;--vz-dark-border-subtle:#adb5bd;--vz-white-rgb:255,255,255;--vz-black-rgb:0,0,0;--vz-font-sans-serif:"IBM Plex Sans",sans-serif;--vz-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--vz-gradient:linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));--vz-body-font-family:var(--vz-font-sans-serif);--vz-body-font-size:0.875rem;--vz-body-font-weight:400;--vz-body-line-height:1.5;--vz-body-color:#212529;--vz-body-color-rgb:33,37,41;--vz-body-bg:#f1f1f1;--vz-body-bg-rgb:241,241,241;--vz-emphasis-color:#212529;--vz-emphasis-color-rgb:33,37,41;--vz-secondary-color:#878a99;--vz-secondary-color-rgb:135,138,153;--vz-secondary-bg:#fff;--vz-secondary-bg-rgb:255,255,255;--vz-tertiary-color:rgba(33, 37, 41, 0.5);--vz-tertiary-color-rgb:33,37,41;--vz-tertiary-bg:#eff2f7;--vz-tertiary-bg-rgb:239,242,247;--vz-heading-color:#495057;--vz-link-color:#5ea3cb;--vz-link-color-rgb:94,163,203;--vz-link-decoration:none;--vz-link-hover-color:#5ea3cb;--vz-link-hover-color-rgb:94,163,203;--vz-code-color:#f672a7;--vz-highlight-color:#212529;--vz-highlight-bg:#fcf8e3;--vz-border-width:1px;--vz-border-style:solid;--vz-border-color:#e9ebec;--vz-border-color-translucent:#ced4da;--vz-border-radius:0.25rem;--vz-border-radius-sm:0.2rem;--vz-border-radius-lg:0.3rem;--vz-border-radius-xl:1rem;--vz-border-radius-xxl:2rem;--vz-border-radius-2xl:var(--vz-border-radius-xxl);--vz-border-radius-pill:50rem;--vz-box-shadow:0 1px 2px rgba(56, 65, 74, 0.15);--vz-box-shadow-sm:0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);--vz-box-shadow-lg:0 5px 10px rgba(30, 32, 37, 0.12);--vz-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, 0.075);--vz-focus-ring-width:0.25rem;--vz-focus-ring-opacity:0.25;--vz-focus-ring-color:rgba(var(--vz-primary-rgb), 0.25);--vz-form-valid-color:#6ada7d;--vz-form-valid-border-color:#6ada7d;--vz-form-invalid-color:#fa896b;--vz-form-invalid-border-color:#fa896b}[data-bs-theme=dark]{color-scheme:dark;--vz-body-color:#ced4da;--vz-body-color-rgb:206,212,218;--vz-body-bg:#1a1d21;--vz-body-bg-rgb:26,29,33;--vz-emphasis-color:#fff;--vz-emphasis-color-rgb:255,255,255;--vz-secondary-color:#878a99;--vz-secondary-color-rgb:135,138,153;--vz-secondary-bg:#212529;--vz-secondary-bg-rgb:33,37,41;--vz-tertiary-color:rgba(206, 212, 218, 0.75);--vz-tertiary-color-rgb:206,212,218;--vz-tertiary-bg:#2a2d31;--vz-tertiary-bg-rgb:42,45,49;--vz-primary-text-emphasis:#7eb5d5;--vz-secondary-text-emphasis:#8d9dd2;--vz-success-text-emphasis:#88e197;--vz-info-text-emphasis:#79d5ee;--vz-warning-text-emphasis:#f9c66f;--vz-danger-text-emphasis:#fba189;--vz-light-text-emphasis:#535659;--vz-dark-text-emphasis:#5f6164;--vz-primary-bg-subtle:rgba(94, 163, 203, 0.15);--vz-secondary-bg-subtle:rgba(112, 132, 199, 0.15);--vz-success-bg-subtle:rgba(106, 218, 125, 0.15);--vz-info-bg-subtle:rgba(88, 202, 234, 0.15);--vz-warning-bg-subtle:rgba(247, 184, 75, 0.15);--vz-danger-bg-subtle:rgba(250, 137, 107, 0.15);--vz-light-bg-subtle:#25282c;--vz-dark-bg-subtle:#313437;--vz-primary-border-subtle:#3d6a84;--vz-secondary-border-subtle:#384264;--vz-success-border-subtle:#356d3f;--vz-info-border-subtle:#2c6575;--vz-warning-border-subtle:#7c5c26;--vz-danger-border-subtle:#7d4536;--vz-light-border-subtle:#35383c;--vz-dark-border-subtle:#3c3f42;--vz-heading-color:#ced4da;--vz-link-color:#dfedf5;--vz-link-hover-color:#e5f1f7;--vz-link-color-rgb:223,237,245Line truncated
/*# sourceMappingURL=bootstrap-rtl.min.css.map */
+14173
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
@charset "UTF-8";@import url(https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap);/*!
* Bootstrap v5.3.2 (https://getbootstrap.com/)
* Copyright 2011-2023 The Bootstrap Authors
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/:root,[data-bs-theme=light]{--vz-blue:#5ea3cb;--vz-indigo:#405189;--vz-purple:#7084c7;--vz-pink:#f672a7;--vz-red:#fa896b;--vz-orange:#f1963b;--vz-yellow:#f7b84b;--vz-green:#6ada7d;--vz-teal:#02a8b5;--vz-cyan:#58caea;--vz-white:#fff;--vz-gray:#878a99;--vz-gray-dark:#343a40;--vz-gray-100:#f3f6f9;--vz-gray-200:#eff2f7;--vz-gray-300:#e9ebec;--vz-gray-400:#ced4da;--vz-gray-500:#adb5bd;--vz-gray-600:#878a99;--vz-gray-700:#495057;--vz-gray-800:#343a40;--vz-gray-900:#212529;--vz-primary:#5ea3cb;--vz-secondary:#7084c7;--vz-success:#6ada7d;--vz-info:#58caea;--vz-warning:#f7b84b;--vz-danger:#fa896b;--vz-light:#f3f6f9;--vz-dark:#212529;--vz-primary-rgb:94,163,203;--vz-secondary-rgb:112,132,199;--vz-success-rgb:106,218,125;--vz-info-rgb:88,202,234;--vz-warning-rgb:247,184,75;--vz-danger-rgb:250,137,107;--vz-light-rgb:243,246,249;--vz-dark-rgb:33,37,41;--vz-primary-text-emphasis:#508bad;--vz-secondary-text-emphasis:#5f70a9;--vz-success-text-emphasis:#5ab96a;--vz-info-text-emphasis:#4bacc7;--vz-warning-text-emphasis:#d29c40;--vz-danger-text-emphasis:#d5745b;--vz-light-text-emphasis:#ced4da;--vz-dark-text-emphasis:#343a40;--vz-primary-bg-subtle:#e7f1f7;--vz-secondary-bg-subtle:#eaedf7;--vz-success-bg-subtle:#e9f9ec;--vz-info-bg-subtle:#e6f7fc;--vz-warning-bg-subtle:#fef4e4;--vz-danger-bg-subtle:#feede9;--vz-light-bg-subtle:#f9fbfc;--vz-dark-bg-subtle:#e9ebec;--vz-primary-border-subtle:#bfdaea;--vz-secondary-border-subtle:#c6cee9;--vz-success-border-subtle:#c3f0cb;--vz-info-border-subtle:#bceaf7;--vz-warning-border-subtle:#fce3b7;--vz-danger-border-subtle:#fdd0c4;--vz-light-border-subtle:#eff2f7;--vz-dark-border-subtle:#adb5bd;--vz-white-rgb:255,255,255;--vz-black-rgb:0,0,0;--vz-font-sans-serif:"IBM Plex Sans",sans-serif;--vz-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--vz-gradient:linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));--vz-body-font-family:var(--vz-font-sans-serif);--vz-body-font-size:0.875rem;--vz-body-font-weight:400;--vz-body-line-height:1.5;--vz-body-color:#212529;--vz-body-color-rgb:33,37,41;--vz-body-bg:#f1f1f1;--vz-body-bg-rgb:241,241,241;--vz-emphasis-color:#212529;--vz-emphasis-color-rgb:33,37,41;--vz-secondary-color:#878a99;--vz-secondary-color-rgb:135,138,153;--vz-secondary-bg:#fff;--vz-secondary-bg-rgb:255,255,255;--vz-tertiary-color:rgba(33, 37, 41, 0.5);--vz-tertiary-color-rgb:33,37,41;--vz-tertiary-bg:#eff2f7;--vz-tertiary-bg-rgb:239,242,247;--vz-heading-color:#495057;--vz-link-color:#5ea3cb;--vz-link-color-rgb:94,163,203;--vz-link-decoration:none;--vz-link-hover-color:#5ea3cb;--vz-link-hover-color-rgb:94,163,203;--vz-code-color:#f672a7;--vz-highlight-color:#212529;--vz-highlight-bg:#fcf8e3;--vz-border-width:1px;--vz-border-style:solid;--vz-border-color:#e9ebec;--vz-border-color-translucent:#ced4da;--vz-border-radius:0.25rem;--vz-border-radius-sm:0.2rem;--vz-border-radius-lg:0.3rem;--vz-border-radius-xl:1rem;--vz-border-radius-xxl:2rem;--vz-border-radius-2xl:var(--vz-border-radius-xxl);--vz-border-radius-pill:50rem;--vz-box-shadow:0 1px 2px rgba(56, 65, 74, 0.15);--vz-box-shadow-sm:0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);--vz-box-shadow-lg:0 5px 10px rgba(30, 32, 37, 0.12);--vz-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, 0.075);--vz-focus-ring-width:0.25rem;--vz-focus-ring-opacity:0.25;--vz-focus-ring-color:rgba(var(--vz-primary-rgb), 0.25);--vz-form-valid-color:#6ada7d;--vz-form-valid-border-color:#6ada7d;--vz-form-invalid-color:#fa896b;--vz-form-invalid-border-color:#fa896b}[data-bs-theme=dark]{color-scheme:dark;--vz-body-color:#ced4da;--vz-body-color-rgb:206,212,218;--vz-body-bg:#1a1d21;--vz-body-bg-rgb:26,29,33;--vz-emphasis-color:#fff;--vz-emphasis-color-rgb:255,255,255;--vz-secondary-color:#878a99;--vz-secondary-color-rgb:135,138,153;--vz-secondary-bg:#212529;--vz-secondary-bg-rgb:33,37,41;--vz-tertiary-color:rgba(206, 212, 218, 0.75);--vz-tertiary-color-rgb:206,212,218;--vz-tertiary-bg:#2a2d31;--vz-tertiary-bg-rgb:42,45,49;--vz-primary-text-emphasis:#7eb5d5;--vz-secondary-text-emphasis:#8d9dd2;--vz-success-text-emphasis:#88e197;--vz-info-text-emphasis:#79d5ee;--vz-warning-text-emphasis:#f9c66f;--vz-danger-text-emphasis:#fba189;--vz-light-text-emphasis:#535659;--vz-dark-text-emphasis:#5f6164;--vz-primary-bg-subtle:rgba(94, 163, 203, 0.15);--vz-secondary-bg-subtle:rgba(112, 132, 199, 0.15);--vz-success-bg-subtle:rgba(106, 218, 125, 0.15);--vz-info-bg-subtle:rgba(88, 202, 234, 0.15);--vz-warning-bg-subtle:rgba(247, 184, 75, 0.15);--vz-danger-bg-subtle:rgba(250, 137, 107, 0.15);--vz-light-bg-subtle:#25282c;--vz-dark-bg-subtle:#313437;--vz-primary-border-subtle:#3d6a84;--vz-secondary-border-subtle:#384264;--vz-success-border-subtle:#356d3f;--vz-info-border-subtle:#2c6575;--vz-warning-border-subtle:#7c5c26;--vz-danger-border-subtle:#7d4536;--vz-light-border-subtle:#35383c;--vz-dark-border-subtle:#3c3f42;--vz-heading-color:#ced4da;--vz-link-color:#dfedf5;--vz-link-hover-color:#e5f1f7;--vz-link-color-rgb:223,237,245Line truncated
/*# sourceMappingURL=bootstrap.min.css.map */
+2
View File
@@ -0,0 +1,2 @@
/*# sourceMappingURL=custom-rtl.min.css.map */
@@ -0,0 +1,31 @@
/* Segmented Control Delicado */
.segmented-control {
background: #f8f9fa;
border-radius: 2rem;
padding: 4px 8px;
display: flex;
gap: 0.5rem;
align-items: center;
}
.segmented-control .seg-btn {
border: none;
background: transparent;
color: #0d6efd;
font-weight: 500;
border-radius: 2rem;
padding: 0.5rem 1.5rem;
transition: background 0.18s, color 0.18s, box-shadow 0.18s;
box-shadow: none;
outline: none;
}
.segmented-control .seg-btn.active {
background: #e7f1ff;
color: #0d6efd;
box-shadow: 0 2px 8px 0 rgba(13,110,253,0.08);
font-weight: 600;
}
.segmented-control .seg-btn:hover:not(.active),
.segmented-control .seg-btn:focus-visible:not(.active) {
background: #f1f3f6;
color: #0d6efd;
}
+58
View File
@@ -0,0 +1,58 @@
/*
Template Name: BitReport CRM - Sistema de Gestão Empresarial
Author: BitReport
Website: https://bitreport.pt/
Contact: [email protected]
File: Custom Css File
*/
.price-col {
display: inline-block;
max-width: 70px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.referencia-col {
display: inline-block;
max-width: 110px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.ean-col {
display: inline-block;
max-width: 13ch;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.brand-col {
display: inline-block;
max-width: 80px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.supplier-col {
display: inline-block;
max-width: 90px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.product-name-ellipsis {
display: inline-block;
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
vertical-align: middle;
font-weight: 500;
font-size: 1rem;
}
+2
View File
@@ -0,0 +1,2 @@
/*# sourceMappingURL=custom.min.css.map */
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
@font-face{font-family:"Material Design Icons";src:url(../fonts/materialdesignicons-webfont.eot?v=7.2.96);src:url(../fonts/materialdesignicons-webfont.eot?#iefix&v=7.2.96) format("embedded-opentype"),url(../fonts/materialdesignicons-webfont.woff2?v=7.2.96) format("woff2"),url(../fonts/materialdesignicons-webfont.woff?v=7.2.96) format("woff"),url(../fonts/materialdesignicons-webfont.ttf?v=7.2.96) format("truetype");font-weight:400;font-style:normal}.mdi-set,.mdi:before{display:inline-block;font:normal normal normal 24px/1 "Material Design Icons";font-size:inherit;text-rendering:auto;line-height:inherit;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.mdi-ab-testing::before{content:"\f01c9"}.mdi-abacus::before{content:"\f16e0"}.mdi-abjad-arabic::before{content:"\f1328"}.mdi-abjad-hebrew::before{content:"\f1329"}.mdi-abugida-devanagari::before{content:"\f132a"}.mdi-abugida-thai::before{content:"\f132b"}.mdi-access-point::before{content:"\f0003"}.mdi-access-point-check::before{content:"\f1538"}.mdi-access-point-minus::before{content:"\f1539"}.mdi-access-point-network::before{content:"\f0002"}.mdi-access-point-network-off::before{content:"\f0be1"}.mdi-access-point-off::before{content:"\f1511"}.mdi-access-point-plus::before{content:"\f153a"}.mdi-access-point-remove::before{content:"\f153b"}.mdi-account::before{content:"\f0004"}.mdi-account-alert::before{content:"\f0005"}.mdi-account-alert-outline::before{content:"\f0b50"}.mdi-account-arrow-down::before{content:"\f1868"}.mdi-account-arrow-down-outline::before{content:"\f1869"}.mdi-account-arrow-left::before{content:"\f0b51"}.mdi-account-arrow-left-outline::before{content:"\f0b52"}.mdi-account-arrow-right::before{content:"\f0b53"}.mdi-account-arrow-right-outline::before{content:"\f0b54"}.mdi-account-arrow-up::before{content:"\f1867"}.mdi-account-arrow-up-outline::before{content:"\f186a"}.mdi-account-badge::before{content:"\f1b0a"}.mdi-account-badge-outline::before{content:"\f1b0b"}.mdi-account-box::before{content:"\f0006"}.mdi-account-box-multiple::before{content:"\f0934"}.mdi-account-box-multiple-outline::before{content:"\f100a"}.mdi-account-box-outline::before{content:"\f0007"}.mdi-account-cancel::before{content:"\f12df"}.mdi-account-cancel-outline::before{content:"\f12e0"}.mdi-account-card::before{content:"\f1ba4"}.mdi-account-card-outline::before{content:"\f1ba5"}.mdi-account-cash::before{content:"\f1097"}.mdi-account-cash-outline::before{content:"\f1098"}.mdi-account-check::before{content:"\f0008"}.mdi-account-check-outline::before{content:"\f0be2"}.mdi-account-child::before{content:"\f0a89"}.mdi-account-child-circle::before{content:"\f0a8a"}.mdi-account-child-outline::before{content:"\f10c8"}.mdi-account-circle::before{content:"\f0009"}.mdi-account-circle-outline::before{content:"\f0b55"}.mdi-account-clock::before{content:"\f0b56"}.mdi-account-clock-outline::before{content:"\f0b57"}.mdi-account-cog::before{content:"\f1370"}.mdi-account-cog-outline::before{content:"\f1371"}.mdi-account-convert::before{content:"\f000a"}.mdi-account-convert-outline::before{content:"\f1301"}.mdi-account-cowboy-hat::before{content:"\f0e9b"}.mdi-account-cowboy-hat-outline::before{content:"\f17f3"}.mdi-account-credit-card::before{content:"\f1ba6"}.mdi-account-credit-card-outline::before{content:"\f1ba7"}.mdi-account-details::before{content:"\f0631"}.mdi-account-details-outline::before{content:"\f1372"}.mdi-account-edit::before{content:"\f06bc"}.mdi-account-edit-outline::before{content:"\f0ffb"}.mdi-account-eye::before{content:"\f0420"}.mdi-account-eye-outline::before{content:"\f127b"}.mdi-account-filter::before{content:"\f0936"}.mdi-account-filter-outline::before{content:"\f0f9d"}.mdi-account-group::before{content:"\f0849"}.mdi-account-group-outline::before{content:"\f0b58"}.mdi-account-hard-hat::before{content:"\f05b5"}.mdi-account-hard-hat-outline::before{content:"\f1a1f"}.mdi-account-heart::before{content:"\f0899"}.mdi-account-heart-outline::before{content:"\f0be3"}.mdi-account-injury::before{content:"\f1815"}.mdi-account-injury-outline::before{content:"\f1816"}.mdi-account-key::before{content:"\f000b"}.mdi-account-key-outline::before{content:"\f0be4"}.mdi-account-lock::before{content:"\f115e"}.mdi-account-lock-open::before{content:"\f1960"}.mdi-account-lock-open-outline::before{content:"\f1961"}.mdi-account-lock-outline::before{content:"\f115f"}.mdi-account-minus::before{content:"\f000d"}.mdi-account-minus-outline::before{content:"\f0aec"}.mdi-account-multiple::before{content:"\f000e"}.mdi-account-multiple-check::before{content:"\f08c5"}.mdi-account-multiple-check-outline::before{content:"\f11fe"}.mdi-account-multiple-minus::before{content:"\f05d3"}.mdi-account-multiple-minus-outline::before{content:"\f0be5"}.mdi-account-multiple-outline::before{content:"\f000f"}.mdi-account-multiple-plus::before{content:"\f0010"}.mdi-account-multiple-plus-outline::before{content:"\f0800"}.mdi-account-multiple-remove::before{content:"\f120a"}.mdi-account-multiple-remove-outLine truncated
Binary file not shown.
Loaded 100 of 3716 files, more files were not shown because too many files have changed in this diff. Show more