Files
1sonhador 831145b2c4 refactor: Remove ScriptBuilderService from MoneyFlix
- Remove ScriptBuilderService and ScriptBuilderIntegrationService (CRM-specific)
- Update controllers to use GoogleSheetsService instead
- Disable script generation/deployment functionality temporarily
- Fix creative count TODO in AdvertisingController
- Clean up module service registrations
- Restore clean User Views files

ScriptBuilder functionality is specific to the main CRM and not needed for MoneyFlix.
2025-10-28 16:18:30 +00:00

543 lines
17 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Advertising\Services;
use App\Core\DatabaseManager;
use App\Core\ErrorReporter;
/**
* Brand Detection Service
*
* Configurable brand detection system based on URL patterns, domains, paths, etc.
* Brand Detection Service for MoneyFlix
* Flexible brand detection with configurable rules.
*/
class BrandDetectionService
{
private DatabaseManager $db;
public function __construct()
{
$this->db = DatabaseManager::getInstance();
}
/**
* Detect brand from URL using configurable rules
*/
public function detectBrandFromUrl(string $url): ?array
{
try {
// Parse URL
$parsedUrl = parse_url($url);
if (!$parsedUrl) {
return null;
}
// Get all active detection rules ordered by priority
$rules = $this->getActiveDetectionRules();
foreach ($rules as $rule) {
$match = $this->evaluateRule($rule, $parsedUrl, $url);
if ($match) {
return [
'brand_id' => $rule['brand_id'],
'brand_name' => $this->getBrandName($rule['brand_id']),
'rule_id' => $rule['id'],
'rule_name' => $rule['name'],
'match_data' => $match,
'confidence' => $this->calculateConfidence($rule, $match)
];
}
}
return null;
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'brand_detection',
'url' => $url
]);
return null;
}
}
/**
* Get all active detection rules ordered by priority
*/
private function getActiveDetectionRules(): array
{
$sql = "
SELECT
dr.id AS rule_id,
dr.brand_id AS brand_id,
dr.pattern_type AS pattern_type,
dr.pattern_value AS pattern_value,
dr.priority AS rule_priority,
dr.is_active AS is_active,
dr.status AS rule_status,
dr.created_at AS created_date,
dr.updated_at AS updated_date
FROM
advertising_detection_rules dr
WHERE
dr.is_active = 1 AND dr.status >= 0
ORDER BY
dr.priority DESC, dr.id ASC
";
return $this->db->fetchAll($sql) ?: [];
}
/**
* Evaluate a single detection rule against the URL
*/
private function evaluateRule(array $rule, array $parsedUrl, string $fullUrl): ?array
{
$ruleType = $rule['rule_type'];
$pattern = $rule['rule_pattern'];
$conditions = json_decode($rule['rule_conditions'] ?? '{}', true) ?: [];
switch ($ruleType) {
case 'regex':
return $this->evaluateRegexRule($pattern, $fullUrl, $conditions);
case 'domain':
return $this->evaluateDomainRule($pattern, $parsedUrl, $conditions);
case 'path':
return $this->evaluatePathRule($pattern, $parsedUrl, $conditions);
case 'parameter':
return $this->evaluateParameterRule($pattern, $parsedUrl, $conditions);
case 'custom':
return $this->evaluateCustomRule($pattern, $parsedUrl, $fullUrl, $conditions);
default:
return null;
}
}
/**
* Evaluate regex-based rule
*/
private function evaluateRegexRule(string $pattern, string $url, array $conditions): ?array
{
if (preg_match($pattern, $url, $matches)) {
$extractedData = $this->extractDataFromMatches($matches, $conditions);
if ($this->validateConditions($extractedData, $conditions)) {
return [
'type' => 'regex',
'matches' => $matches,
'extracted_data' => $extractedData
];
}
}
return null;
}
/**
* Evaluate domain-based rule
*/
private function evaluateDomainRule(string $pattern, array $parsedUrl, array $conditions): ?array
{
$host = $parsedUrl['host'] ?? '';
// Support wildcard domains
$pattern = str_replace(['*', '.'], ['[^.]+', '\.'], $pattern);
$pattern = '/^' . $pattern . '$/i';
if (preg_match($pattern, $host)) {
$extractedData = [
'domain' => $host,
'subdomain' => $this->extractSubdomain($host)
];
if ($this->validateConditions($extractedData, $conditions)) {
return [
'type' => 'domain',
'domain' => $host,
'extracted_data' => $extractedData
];
}
}
return null;
}
/**
* Evaluate path-based rule
*/
private function evaluatePathRule(string $pattern, array $parsedUrl, array $conditions): ?array
{
$path = $parsedUrl['path'] ?? '';
// Support path patterns with parameters
$pattern = str_replace(['*', '/'], ['[^/]+', '\/'], $pattern);
$pattern = '/^' . $pattern . '$/i';
if (preg_match($pattern, $path, $matches)) {
$extractedData = [
'path' => $path,
'path_parts' => explode('/', trim($path, '/'))
];
if ($this->validateConditions($extractedData, $conditions)) {
return [
'type' => 'path',
'path' => $path,
'matches' => $matches,
'extracted_data' => $extractedData
];
}
}
return null;
}
/**
* Evaluate parameter-based rule
*/
private function evaluateParameterRule(string $pattern, array $parsedUrl, array $conditions): ?array
{
$query = $parsedUrl['query'] ?? '';
parse_str($query, $params);
// Pattern can be parameter name or regex for parameter value
if (isset($params[$pattern])) {
$extractedData = [
'parameter' => $pattern,
'value' => $params[$pattern]
];
if ($this->validateConditions($extractedData, $conditions)) {
return [
'type' => 'parameter',
'parameter' => $pattern,
'value' => $params[$pattern],
'extracted_data' => $extractedData
];
}
}
return null;
}
/**
* Evaluate custom rule (JavaScript-like expression)
*/
private function evaluateCustomRule(string $pattern, array $parsedUrl, string $fullUrl, array $conditions): ?array
{
// Custom rules can use PHP expressions
$variables = [
'url' => $fullUrl,
'host' => $parsedUrl['host'] ?? '',
'path' => $parsedUrl['path'] ?? '',
'query' => $parsedUrl['query'] ?? '',
'scheme' => $parsedUrl['scheme'] ?? '',
'port' => $parsedUrl['port'] ?? null,
'fragment' => $parsedUrl['fragment'] ?? ''
];
// Create a safe evaluation environment
$expression = $this->sanitizeCustomExpression($pattern);
try {
// Use eval in a controlled way (only for trusted expressions)
$result = eval("return $expression;");
if ($result) {
$extractedData = [
'custom_result' => $result,
'variables' => $variables
];
if ($this->validateConditions($extractedData, $conditions)) {
return [
'type' => 'custom',
'result' => $result,
'extracted_data' => $extractedData
];
}
}
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'custom_rule_evaluation',
'expression' => $expression
]);
}
return null;
}
/**
* Extract data from regex matches using extraction rules
*/
private function extractDataFromMatches(array $matches, array $conditions): array
{
$extractedData = [];
// Extract named groups
foreach ($matches as $key => $value) {
if (is_string($key)) {
$extractedData[$key] = $value;
}
}
// Apply custom extraction rules from conditions
if (isset($conditions['extraction'])) {
foreach ($conditions['extraction'] as $target => $source) {
if (isset($matches[$source])) {
$extractedData[$target] = $matches[$source];
}
}
}
return $extractedData;
}
/**
* Validate extracted data against conditions
*/
private function validateConditions(array $extractedData, array $conditions): bool
{
if (empty($conditions['validation'])) {
return true;
}
foreach ($conditions['validation'] as $field => $rules) {
$value = $extractedData[$field] ?? null;
foreach ($rules as $rule => $expected) {
if (!$this->validateField($value, $rule, $expected)) {
return false;
}
}
}
return true;
}
/**
* Validate a single field against a rule
*/
private function validateField($value, string $rule, $expected): bool
{
switch ($rule) {
case 'required':
return !empty($value);
case 'min_length':
return strlen($value) >= $expected;
case 'max_length':
return strlen($value) <= $expected;
case 'pattern':
return preg_match($expected, $value);
case 'in':
return in_array($value, (array)$expected);
case 'not_in':
return !in_array($value, (array)$expected);
case 'starts_with':
return strpos($value, $expected) === 0;
case 'ends_with':
return strpos($value, $expected) === (strlen($value) - strlen($expected));
case 'contains':
return strpos($value, $expected) !== false;
default:
return true;
}
}
/**
* Calculate confidence score for a match
*/
private function calculateConfidence(array $rule, array $match): float
{
$confidence = 0.5; // Base confidence
// Higher priority rules get more confidence
$confidence += min($rule['priority'] / 100, 0.3);
// Regex matches with more groups get more confidence
if ($match['type'] === 'regex' && isset($match['matches'])) {
$confidence += min(count($match['matches']) * 0.1, 0.2);
}
// Domain matches are very reliable
if ($match['type'] === 'domain') {
$confidence += 0.3;
}
return min($confidence, 1.0);
}
/**
* Extract subdomain from host
*/
private function extractSubdomain(string $host): ?string
{
$parts = explode('.', $host);
if (count($parts) > 2) {
return $parts[0];
}
return null;
}
/**
* Sanitize custom expression for safe evaluation
*/
private function sanitizeCustomExpression(string $expression): string
{
// Remove potentially dangerous functions
$dangerous = ['system', 'exec', 'shell_exec', 'passthru', 'eval', 'assert', 'popen', 'proc_open'];
$expression = str_replace($dangerous, '', $expression);
// Only allow safe operations
$expression = preg_replace('/[^a-zA-Z0-9\s\(\)\[\]\{\}\.\-\+\*\/\&\|\!\=\<\>\?\:\,]/', '', $expression);
return $expression;
}
/**
* Get brand name by ID
*/
private function getBrandName(int $brandId): string
{
$brand = $this->db->fetch(
"SELECT name FROM advertising_brands WHERE id = ?",
[$brandId]
);
return $brand['name'] ?? 'Unknown Brand';
}
/**
* Create a new detection rule
*/
public function createDetectionRule(array $data): int
{
$sql = "INSERT INTO advertising_detection_rules (
brand_id, name, description, rule_type, rule_pattern,
rule_conditions, priority, is_active, extraction_rules, fallback_data
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$params = [
$data['brand_id'],
$data['name'],
$data['description'] ?? null,
$data['rule_type'],
$data['rule_pattern'],
json_encode($data['rule_conditions'] ?? []),
$data['priority'] ?? 0,
$data['is_active'] ?? true,
json_encode($data['extraction_rules'] ?? []),
json_encode($data['fallback_data'] ?? [])
];
$this->db->query($sql, $params);
return $this->db->lastInsertId();
}
/**
* Update an existing detection rule
*/
public function updateDetectionRule(int $ruleId, array $data): bool
{
$sql = "UPDATE advertising_detection_rules SET
brand_id = ?, name = ?, description = ?, rule_type = ?, rule_pattern = ?,
rule_conditions = ?, priority = ?, is_active = ?, extraction_rules = ?, fallback_data = ?,
updated_at = NOW()
WHERE id = ?";
$params = [
$data['brand_id'],
$data['name'],
$data['description'] ?? null,
$data['rule_type'],
$data['rule_pattern'],
json_encode($data['rule_conditions'] ?? []),
$data['priority'] ?? 0,
$data['is_active'] ?? true,
json_encode($data['extraction_rules'] ?? []),
json_encode($data['fallback_data'] ?? []),
$ruleId
];
return $this->db->query($sql, $params) > 0;
}
/**
* Soft delete a detection rule (update status to -1)
*/
public function deleteDetectionRule(int $ruleId): bool
{
$sql = "UPDATE advertising_detection_rules SET status = '-1', updated_at = CURRENT_TIMESTAMP WHERE id = ?";
return $this->db->query($sql, [$ruleId]) > 0;
}
/**
* Get detection rules for a brand
*/
public function getDetectionRulesForBrand(int $brandId): array
{
$sql = "SELECT * FROM advertising_detection_rules
WHERE brand_id = ? AND status >= 0
ORDER BY priority DESC, id ASC";
return $this->db->fetchAll($sql, [$brandId]) ?: [];
}
/**
* Test a detection rule against a URL
*/
public function testDetectionRule(int $ruleId, string $url): array
{
$rule = $this->db->fetch("
SELECT
dr.id AS rule_id,
dr.brand_id AS brand_id,
dr.pattern_type AS pattern_type,
dr.pattern_value AS pattern_value,
dr.priority AS rule_priority,
dr.is_active AS is_active,
dr.status AS rule_status
FROM
advertising_detection_rules dr
WHERE
dr.id = ?
", [$ruleId]);
if (!$rule) {
return ['success' => false, 'error' => 'Rule not found'];
}
$parsedUrl = parse_url($url);
if (!$parsedUrl) {
return ['success' => false, 'error' => 'Invalid URL'];
}
$match = $this->evaluateRule($rule, $parsedUrl, $url);
return [
'success' => true,
'rule' => $rule,
'url' => $url,
'parsed_url' => $parsedUrl,
'match' => $match,
'matched' => $match !== null
];
}
}