- Fix storage permissions to use 'www' user instead of 'www-data' - Fix UserModel getAllForAdmin query to avoid placeholders in LIMIT/OFFSET - Import missing modules: Advertising, Dashboard, Analytics - Update deploy script to copy files to public directory
348 lines
12 KiB
PHP
348 lines
12 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Modules\Advertising\Services;
|
|
|
|
use App\Core\ErrorReporter;
|
|
use App\Core\Logger;
|
|
|
|
class TemplateValidationService
|
|
{
|
|
private Logger $logger;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->logger = new Logger('debug');
|
|
}
|
|
|
|
/**
|
|
* Validar URL do template
|
|
*/
|
|
public function validateTemplateUrl(string $url): array
|
|
{
|
|
$result = [
|
|
'valid' => false,
|
|
'errors' => [],
|
|
'warnings' => [],
|
|
'suggestions' => []
|
|
];
|
|
|
|
try {
|
|
// Verificar se é uma URL válida
|
|
if (!filter_var($url, FILTER_VALIDATE_URL)) {
|
|
$result['errors'][] = 'URL inválida';
|
|
return $result;
|
|
}
|
|
|
|
// Verificar protocolo
|
|
$parsedUrl = parse_url($url);
|
|
if (!isset($parsedUrl['scheme']) || !in_array($parsedUrl['scheme'], ['http', 'https'])) {
|
|
$result['errors'][] = 'Protocolo deve ser HTTP ou HTTPS';
|
|
return $result;
|
|
}
|
|
|
|
// Verificar se contém variáveis de template
|
|
if (!preg_match('/\{[^}]+\}/', $url)) {
|
|
$result['warnings'][] = 'URL não contém variáveis de template (ex: {tracker_id})';
|
|
}
|
|
|
|
// Verificar variáveis comuns
|
|
$commonVars = ['tracker_id', 'code', 'campaign_alias', 'affiliate_id', 'click_id'];
|
|
$foundVars = [];
|
|
foreach ($commonVars as $var) {
|
|
if (strpos($url, '{' . $var . '}') !== false) {
|
|
$foundVars[] = $var;
|
|
}
|
|
}
|
|
|
|
if (empty($foundVars)) {
|
|
$result['suggestions'][] = 'Considere usar variáveis padrão: tracker_id, code, campaign_alias';
|
|
}
|
|
|
|
// Verificar se a URL é acessível (opcional)
|
|
$this->checkUrlAccessibility($url, $result);
|
|
|
|
$result['valid'] = true;
|
|
$result['found_variables'] = $foundVars;
|
|
|
|
} catch (\Exception $e) {
|
|
$this->logger->error('Erro na validação de URL: ' . $e->getMessage(), [
|
|
'url' => $url,
|
|
'error' => $e->getMessage()
|
|
]);
|
|
$result['errors'][] = 'Erro interno na validação: ' . $e->getMessage();
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Verificar acessibilidade da URL
|
|
*/
|
|
private function checkUrlAccessibility(string $url, array &$result): void
|
|
{
|
|
try {
|
|
$context = stream_context_create([
|
|
'http' => [
|
|
'timeout' => 5,
|
|
'user_agent' => 'BitReport-CRM/1.0'
|
|
]
|
|
]);
|
|
|
|
$headers = @get_headers($url, true, $context);
|
|
|
|
if ($headers === false) {
|
|
$result['warnings'][] = 'Não foi possível verificar a acessibilidade da URL';
|
|
return;
|
|
}
|
|
|
|
$statusCode = $this->extractStatusCode($headers);
|
|
|
|
if ($statusCode >= 200 && $statusCode < 300) {
|
|
$result['suggestions'][] = 'URL acessível (Status: ' . $statusCode . ')';
|
|
} elseif ($statusCode >= 400) {
|
|
$result['warnings'][] = 'URL pode não estar acessível (Status: ' . $statusCode . ')';
|
|
}
|
|
|
|
} catch (\Exception $e) {
|
|
$result['warnings'][] = 'Erro ao verificar acessibilidade: ' . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Extrair código de status dos headers
|
|
*/
|
|
private function extractStatusCode(array $headers): int
|
|
{
|
|
if (isset($headers[0])) {
|
|
if (preg_match('/HTTP\/\d\.\d\s+(\d+)/', $headers[0], $matches)) {
|
|
return (int) $matches[1];
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/**
|
|
* Validar variáveis do template
|
|
*/
|
|
public function validateTemplateVariables(array $variables): array
|
|
{
|
|
$result = [
|
|
'valid' => true,
|
|
'errors' => [],
|
|
'warnings' => [],
|
|
'suggestions' => []
|
|
];
|
|
|
|
try {
|
|
foreach ($variables as $key => $value) {
|
|
// Validar nome da variável
|
|
if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $key)) {
|
|
$result['errors'][] = "Nome de variável inválido: '$key'";
|
|
$result['valid'] = false;
|
|
}
|
|
|
|
// Verificar se é muito longo
|
|
if (strlen($key) > 50) {
|
|
$result['warnings'][] = "Nome de variável muito longo: '$key'";
|
|
}
|
|
|
|
// Verificar se é muito curto
|
|
if (strlen($key) < 2) {
|
|
$result['warnings'][] = "Nome de variável muito curto: '$key'";
|
|
}
|
|
}
|
|
|
|
// Verificar variáveis obrigatórias
|
|
$requiredVars = ['tracker_id'];
|
|
foreach ($requiredVars as $required) {
|
|
if (!array_key_exists($required, $variables)) {
|
|
$result['suggestions'][] = "Considere adicionar a variável obrigatória: '$required'";
|
|
}
|
|
}
|
|
|
|
} catch (\Exception $e) {
|
|
$this->logger->error('Erro na validação de variáveis: ' . $e->getMessage(), [
|
|
'variables' => $variables,
|
|
'error' => $e->getMessage()
|
|
]);
|
|
$result['errors'][] = 'Erro interno na validação: ' . $e->getMessage();
|
|
$result['valid'] = false;
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Validar script de tracking
|
|
*/
|
|
public function validateTrackingScript(string $script): array
|
|
{
|
|
$result = [
|
|
'valid' => true,
|
|
'errors' => [],
|
|
'warnings' => [],
|
|
'suggestions' => []
|
|
];
|
|
|
|
try {
|
|
// Verificar se contém variáveis de template
|
|
if (!preg_match('/\{[^}]+\}/', $script)) {
|
|
$result['warnings'][] = 'Script não contém variáveis de template';
|
|
}
|
|
|
|
// Verificar se contém elementos básicos de tracking
|
|
$trackingElements = ['track', 'pixel', 'img', 'script', 'analytics'];
|
|
$foundElements = [];
|
|
foreach ($trackingElements as $element) {
|
|
if (stripos($script, $element) !== false) {
|
|
$foundElements[] = $element;
|
|
}
|
|
}
|
|
|
|
if (empty($foundElements)) {
|
|
$result['suggestions'][] = 'Considere incluir elementos de tracking (pixel, script, analytics)';
|
|
}
|
|
|
|
// Verificar se é muito longo
|
|
if (strlen($script) > 5000) {
|
|
$result['warnings'][] = 'Script muito longo (' . strlen($script) . ' caracteres)';
|
|
}
|
|
|
|
// Verificar se é muito curto
|
|
if (strlen($script) < 10) {
|
|
$result['warnings'][] = 'Script muito curto';
|
|
}
|
|
|
|
} catch (\Exception $e) {
|
|
$this->logger->error('Erro na validação de script: ' . $e->getMessage(), [
|
|
'script_length' => strlen($script),
|
|
'error' => $e->getMessage()
|
|
]);
|
|
$result['errors'][] = 'Erro interno na validação: ' . $e->getMessage();
|
|
$result['valid'] = false;
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Validar template completo
|
|
*/
|
|
public function validateTemplate(array $templateData): array
|
|
{
|
|
$result = [
|
|
'valid' => true,
|
|
'errors' => [],
|
|
'warnings' => [],
|
|
'suggestions' => [],
|
|
'details' => []
|
|
];
|
|
|
|
try {
|
|
// Validar URL
|
|
if (!empty($templateData['template_url'])) {
|
|
$urlValidation = $this->validateTemplateUrl($templateData['template_url']);
|
|
$result['details']['url'] = $urlValidation;
|
|
|
|
if (!$urlValidation['valid']) {
|
|
$result['valid'] = false;
|
|
}
|
|
|
|
$result['errors'] = array_merge($result['errors'], $urlValidation['errors']);
|
|
$result['warnings'] = array_merge($result['warnings'], $urlValidation['warnings']);
|
|
$result['suggestions'] = array_merge($result['suggestions'], $urlValidation['suggestions']);
|
|
}
|
|
|
|
// Validar variáveis
|
|
if (!empty($templateData['template_variables'])) {
|
|
$vars = is_string($templateData['template_variables'])
|
|
? json_decode($templateData['template_variables'], true)
|
|
: $templateData['template_variables'];
|
|
|
|
if (is_array($vars)) {
|
|
$varsValidation = $this->validateTemplateVariables($vars);
|
|
$result['details']['variables'] = $varsValidation;
|
|
|
|
if (!$varsValidation['valid']) {
|
|
$result['valid'] = false;
|
|
}
|
|
|
|
$result['errors'] = array_merge($result['errors'], $varsValidation['errors']);
|
|
$result['warnings'] = array_merge($result['warnings'], $varsValidation['warnings']);
|
|
$result['suggestions'] = array_merge($result['suggestions'], $varsValidation['suggestions']);
|
|
}
|
|
}
|
|
|
|
// Validar script de tracking
|
|
if (!empty($templateData['tracking_script_template'])) {
|
|
$scriptValidation = $this->validateTrackingScript($templateData['tracking_script_template']);
|
|
$result['details']['script'] = $scriptValidation;
|
|
|
|
if (!$scriptValidation['valid']) {
|
|
$result['valid'] = false;
|
|
}
|
|
|
|
$result['errors'] = array_merge($result['errors'], $scriptValidation['errors']);
|
|
$result['warnings'] = array_merge($result['warnings'], $scriptValidation['warnings']);
|
|
$result['suggestions'] = array_merge($result['suggestions'], $scriptValidation['suggestions']);
|
|
}
|
|
|
|
// Remover duplicados
|
|
$result['errors'] = array_unique($result['errors']);
|
|
$result['warnings'] = array_unique($result['warnings']);
|
|
$result['suggestions'] = array_unique($result['suggestions']);
|
|
|
|
} catch (\Exception $e) {
|
|
$this->logger->error('Erro na validação completa do template: ' . $e->getMessage(), [
|
|
'template_data' => $templateData,
|
|
'error' => $e->getMessage()
|
|
]);
|
|
$result['errors'][] = 'Erro interno na validação: ' . $e->getMessage();
|
|
$result['valid'] = false;
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Gerar relatório de validação
|
|
*/
|
|
public function generateValidationReport(array $validationResult): string
|
|
{
|
|
$report = "## Relatório de Validação\n\n";
|
|
|
|
if ($validationResult['valid']) {
|
|
$report .= "✅ **Template válido**\n\n";
|
|
} else {
|
|
$report .= "❌ **Template inválido**\n\n";
|
|
}
|
|
|
|
if (!empty($validationResult['errors'])) {
|
|
$report .= "### Erros:\n";
|
|
foreach ($validationResult['errors'] as $error) {
|
|
$report .= "- ❌ $error\n";
|
|
}
|
|
$report .= "\n";
|
|
}
|
|
|
|
if (!empty($validationResult['warnings'])) {
|
|
$report .= "### Avisos:\n";
|
|
foreach ($validationResult['warnings'] as $warning) {
|
|
$report .= "- ⚠️ $warning\n";
|
|
}
|
|
$report .= "\n";
|
|
}
|
|
|
|
if (!empty($validationResult['suggestions'])) {
|
|
$report .= "### Sugestões:\n";
|
|
foreach ($validationResult['suggestions'] as $suggestion) {
|
|
$report .= "- 💡 $suggestion\n";
|
|
}
|
|
$report .= "\n";
|
|
}
|
|
|
|
return $report;
|
|
}
|
|
}
|