- 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
753 lines
31 KiB
PHP
753 lines
31 KiB
PHP
<?php
|
||
namespace App\Modules\Advertising\Services;
|
||
|
||
use App\Core\DatabaseManager;
|
||
|
||
class ScriptBuilderService
|
||
{
|
||
private DatabaseManager $db;
|
||
private BrandDetectionService $brandDetectionService;
|
||
private string $outputPath;
|
||
private string $templatePath;
|
||
|
||
public function __construct()
|
||
{
|
||
$this->db = DatabaseManager::getInstance();
|
||
$this->brandDetectionService = new BrandDetectionService();
|
||
$this->outputPath = __DIR__ . '/../../../public/scripts/';
|
||
$this->templatePath = __DIR__ . '/../Templates/';
|
||
|
||
// Criar diretório se não existir
|
||
if (!is_dir($this->outputPath)) {
|
||
mkdir($this->outputPath, 0755, true);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Gerar script para uma campanha
|
||
*/
|
||
public function generateScript(int $campaignId): array
|
||
{
|
||
try {
|
||
// Obter dados da campanha
|
||
$campaign = $this->getCampaignData($campaignId);
|
||
if (!$campaign) {
|
||
throw new \Exception('Campanha não encontrada');
|
||
}
|
||
|
||
// Obter formatos da campanha
|
||
$formats = $this->getFormatsData($campaignId);
|
||
if (empty($formats)) {
|
||
throw new \Exception('Nenhum formato encontrado para a campanha');
|
||
}
|
||
|
||
// Obter trackers
|
||
$trackers = $this->getTrackersData($campaignId);
|
||
|
||
// Obter criativos
|
||
$creatives = $this->getCreativesData($campaignId);
|
||
|
||
// Gerar script baseado no tipo de campanha
|
||
$script = $this->buildScript($campaign, $formats, $trackers, $creatives);
|
||
|
||
// Gerar hash do script
|
||
$scriptHash = md5($script);
|
||
|
||
// Salvar script na base de dados
|
||
$scriptId = $this->saveScript($campaignId, $script, $scriptHash);
|
||
|
||
// Salvar ficheiro
|
||
$fileName = $this->saveScriptFile($scriptId, $script);
|
||
|
||
return [
|
||
'success' => true,
|
||
'script_id' => $scriptId,
|
||
'script_hash' => $scriptHash,
|
||
'file_name' => $fileName,
|
||
'script_preview' => substr($script, 0, 500) . '...'
|
||
];
|
||
|
||
} catch (\Exception $e) {
|
||
error_log("Erro ao gerar script: " . $e->getMessage());
|
||
return [
|
||
'success' => false,
|
||
'error' => $e->getMessage()
|
||
];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Gerar script com deteção configurável de marca
|
||
*/
|
||
public function generateScriptWithBrandDetection(int $campaignId): array
|
||
{
|
||
try {
|
||
// Obter dados da campanha
|
||
$campaign = $this->getCampaignData($campaignId);
|
||
if (!$campaign) {
|
||
throw new \Exception('Campanha não encontrada');
|
||
}
|
||
|
||
// Obter formatos da campanha
|
||
$formats = $this->getFormatsData($campaignId);
|
||
if (empty($formats)) {
|
||
throw new \Exception('Nenhum formato encontrado para a campanha');
|
||
}
|
||
|
||
// Obter trackers
|
||
$trackers = $this->getTrackersData($campaignId);
|
||
|
||
// Obter criativos
|
||
$creatives = $this->getCreativesData($campaignId);
|
||
|
||
// Gerar script com deteção configurável
|
||
$script = $this->buildScriptWithBrandDetection($campaign, $formats, $trackers, $creatives);
|
||
|
||
// Gerar hash do script
|
||
$scriptHash = md5($script);
|
||
|
||
// Salvar script na base de dados
|
||
$scriptId = $this->saveScript($campaignId, $script, $scriptHash);
|
||
|
||
// Salvar ficheiro
|
||
$fileName = $this->saveScriptFile($scriptId, $script);
|
||
|
||
return [
|
||
'success' => true,
|
||
'script_id' => $scriptId,
|
||
'script_hash' => $scriptHash,
|
||
'file_name' => $fileName,
|
||
'script_preview' => substr($script, 0, 500) . '...'
|
||
];
|
||
|
||
} catch (\Exception $e) {
|
||
error_log("Erro ao gerar script com deteção: " . $e->getMessage());
|
||
return [
|
||
'success' => false,
|
||
'error' => $e->getMessage()
|
||
];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Obter dados da campanha
|
||
*/
|
||
private function getCampaignData(int $campaignId): ?array
|
||
{
|
||
$sql = "SELECT * FROM advertising_campaigns WHERE id = :id AND deleted_at IS NULL";
|
||
return $this->db->fetch($sql, [':id' => $campaignId]);
|
||
}
|
||
|
||
/**
|
||
* Obter dados dos formatos
|
||
*/
|
||
private function getFormatsData(int $campaignId): array
|
||
{
|
||
$sql = "SELECT * FROM advertising_formats WHERE campaign_id = :campaign_id AND is_active = 1 ORDER BY weight DESC";
|
||
return $this->db->fetchAll($sql, [':campaign_id' => $campaignId]) ?: [];
|
||
}
|
||
|
||
/**
|
||
* Obter dados dos trackers
|
||
*/
|
||
private function getTrackersData(int $campaignId): array
|
||
{
|
||
$sql = "SELECT t.* FROM advertising_trackers t
|
||
JOIN advertising_formats f ON t.format_id = f.id
|
||
WHERE f.campaign_id = :campaign_id AND t.is_active = 1";
|
||
return $this->db->fetchAll($sql, [':campaign_id' => $campaignId]) ?: [];
|
||
}
|
||
|
||
/**
|
||
* Obter dados dos criativos
|
||
*/
|
||
private function getCreativesData(int $campaignId): array
|
||
{
|
||
$sql = "SELECT cr.* FROM advertising_creatives cr
|
||
JOIN advertising_formats f ON cr.format_id = f.id
|
||
WHERE f.campaign_id = :campaign_id AND cr.is_active = 1";
|
||
return $this->db->fetchAll($sql, [':campaign_id' => $campaignId]) ?: [];
|
||
}
|
||
|
||
/**
|
||
* Construir script baseado no tipo de campanha
|
||
*/
|
||
private function buildScript(array $campaign, array $formats, array $trackers, array $creatives): string
|
||
{
|
||
$scriptType = $campaign['type'];
|
||
|
||
switch ($scriptType) {
|
||
case 'banner':
|
||
return $this->buildBannerScript($campaign, $formats, $trackers, $creatives);
|
||
case 'popup':
|
||
return $this->buildPopupScript($campaign, $formats, $trackers, $creatives);
|
||
case 'native':
|
||
return $this->buildNativeScript($campaign, $formats, $trackers, $creatives);
|
||
default:
|
||
return $this->buildBannerScript($campaign, $formats, $trackers, $creatives);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Construir script com deteção configurável de marca
|
||
*/
|
||
private function buildScriptWithBrandDetection(array $campaign, array $formats, array $trackers, array $creatives): string
|
||
{
|
||
$scriptType = $campaign['type'];
|
||
|
||
switch ($scriptType) {
|
||
case 'banner':
|
||
return $this->buildBannerScriptWithBrandDetection($campaign, $formats, $trackers, $creatives);
|
||
case 'popup':
|
||
return $this->buildPopupScriptWithBrandDetection($campaign, $formats, $trackers, $creatives);
|
||
case 'native':
|
||
return $this->buildNativeScriptWithBrandDetection($campaign, $formats, $trackers, $creatives);
|
||
default:
|
||
return $this->buildBannerScriptWithBrandDetection($campaign, $formats, $trackers, $creatives);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Construir script de banner
|
||
*/
|
||
private function buildBannerScript(array $campaign, array $formats, array $trackers, array $creatives): string
|
||
{
|
||
$script = "// BetZoo Advertising Script - {$campaign['name']}\n";
|
||
$script .= "// Generated: " . date('Y-m-d H:i:s') . "\n\n";
|
||
|
||
$script .= "(function() {\n";
|
||
$script .= " 'use strict';\n\n";
|
||
|
||
// Configurações
|
||
$script .= " const config = {\n";
|
||
$script .= " campaignId: {$campaign['id']},\n";
|
||
$script .= " campaignName: '{$campaign['name']}',\n";
|
||
$script .= " trackingUrl: '" . $this->getTrackingUrl() . "',\n";
|
||
$script .= " formats: " . json_encode($formats) . ",\n";
|
||
$script .= " trackers: " . json_encode($trackers) . ",\n";
|
||
$script .= " creatives: " . json_encode($creatives) . "\n";
|
||
$script .= " };\n\n";
|
||
|
||
// Função de tracking
|
||
$script .= " function trackEvent(eventType, data) {\n";
|
||
$script .= " const trackingData = {\n";
|
||
$script .= " event_type: eventType,\n";
|
||
$script .= " campaign_id: config.campaignId,\n";
|
||
$script .= " session_id: getSessionId(),\n";
|
||
$script .= " timestamp: Date.now(),\n";
|
||
$script .= " ...data\n";
|
||
$script .= " };\n\n";
|
||
|
||
$script .= " fetch(config.trackingUrl + '/api/advertising/tracking/' + eventType, {\n";
|
||
$script .= " method: 'POST',\n";
|
||
$script .= " headers: { 'Content-Type': 'application/json' },\n";
|
||
$script .= " body: JSON.stringify(trackingData)\n";
|
||
$script .= " }).catch(console.error);\n";
|
||
$script .= " }\n\n";
|
||
|
||
// Função para obter session ID
|
||
$script .= " function getSessionId() {\n";
|
||
$script .= " let sessionId = localStorage.getItem('betzoo_session_id');\n";
|
||
$script .= " if (!sessionId) {\n";
|
||
$script .= " sessionId = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);\n";
|
||
$script .= " localStorage.setItem('betzoo_session_id', sessionId);\n";
|
||
$script .= " }\n";
|
||
$script .= " return sessionId;\n";
|
||
$script .= " }\n\n";
|
||
|
||
// Função para criar banner
|
||
$script .= " function createBanner() {\n";
|
||
$script .= " const banner = document.createElement('div');\n";
|
||
$script .= " banner.id = 'betzoo-banner-{$campaign['id']}';\n";
|
||
$script .= " banner.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 9999; background: rgba(0,0,0,0.8); display: flex; align-items: center; justify-content: center;';\n\n";
|
||
|
||
$script .= " const content = document.createElement('div');\n";
|
||
$script .= " content.style.cssText = 'background: white; padding: 20px; border-radius: 8px; max-width: 90%; max-height: 90%; overflow: auto;';\n\n";
|
||
|
||
// Adicionar criativo
|
||
if (!empty($creatives)) {
|
||
$creative = $creatives[0];
|
||
$script .= " const img = document.createElement('img');\n";
|
||
$script .= " img.src = '{$creative['cdn_url']}';\n";
|
||
$script .= " img.alt = '{$creative['alt_text']}';\n";
|
||
$script .= " img.style.cssText = 'max-width: 100%; height: auto; cursor: pointer;';\n";
|
||
$script .= " img.onclick = function() {\n";
|
||
$script .= " trackEvent('click', { creative_id: {$creative['id']} });\n";
|
||
$script .= " if ('{$creative['click_url']}') {\n";
|
||
$script .= " window.open('{$creative['click_url']}', '_blank');\n";
|
||
$script .= " }\n";
|
||
$script .= " };\n";
|
||
$script .= " content.appendChild(img);\n\n";
|
||
}
|
||
|
||
// Botão de fechar
|
||
$script .= " const closeBtn = document.createElement('button');\n";
|
||
$script .= " closeBtn.textContent = '×';\n";
|
||
$script .= " closeBtn.style.cssText = 'position: absolute; top: 10px; right: 10px; background: none; border: none; font-size: 24px; cursor: pointer; color: #666;';\n";
|
||
$script .= " closeBtn.onclick = function() {\n";
|
||
$script .= " document.body.removeChild(banner);\n";
|
||
$script .= " };\n";
|
||
$script .= " content.appendChild(closeBtn);\n\n";
|
||
|
||
$script .= " banner.appendChild(content);\n";
|
||
$script .= " document.body.appendChild(banner);\n\n";
|
||
|
||
// Track view
|
||
if (!empty($trackers)) {
|
||
$tracker = $trackers[0];
|
||
$script .= " trackEvent('view', { tracker_id: {$tracker['id']}, creative_id: " . ($creatives[0]['id'] ?? 0) . " });\n";
|
||
}
|
||
|
||
$script .= " }\n\n";
|
||
|
||
// Auto-executar
|
||
$script .= " // Auto-executar após carregamento\n";
|
||
$script .= " if (document.readyState === 'loading') {\n";
|
||
$script .= " document.addEventListener('DOMContentLoaded', createBanner);\n";
|
||
$script .= " } else {\n";
|
||
$script .= " createBanner();\n";
|
||
$script .= " }\n";
|
||
|
||
$script .= "})();\n";
|
||
|
||
return $script;
|
||
}
|
||
|
||
/**
|
||
* Construir script de banner com deteção configurável de marca
|
||
*/
|
||
private function buildBannerScriptWithBrandDetection(array $campaign, array $formats, array $trackers, array $creatives): string
|
||
{
|
||
$script = "// BetZoo Advertising Script with Configurable Brand Detection - {$campaign['name']}\n";
|
||
$script .= "// Generated: " . date('Y-m-d H:i:s') . "\n\n";
|
||
|
||
$script .= "(function() {\n";
|
||
$script .= " 'use strict';\n\n";
|
||
|
||
// Configurações
|
||
$script .= " const config = {\n";
|
||
$script .= " campaignId: {$campaign['id']},\n";
|
||
$script .= " campaignName: '{$campaign['name']}',\n";
|
||
$script .= " trackingUrl: '" . $this->getTrackingUrl() . "',\n";
|
||
$script .= " formats: " . json_encode($formats) . ",\n";
|
||
$script .= " trackers: " . json_encode($trackers) . ",\n";
|
||
$script .= " creatives: " . json_encode($creatives) . "\n";
|
||
$script .= " };\n\n";
|
||
|
||
// Função de deteção configurável de marca
|
||
$script .= " async function detectBrandFromUrl(url) {\n";
|
||
$script .= " try {\n";
|
||
$script .= " const response = await fetch('" . $this->getTrackingUrl() . "/api/advertising/detection-rules/detect', {\n";
|
||
$script .= " method: 'POST',\n";
|
||
$script .= " headers: { 'Content-Type': 'application/json' },\n";
|
||
$script .= " body: JSON.stringify({ url: url })\n";
|
||
$script .= " });\n";
|
||
$script .= " const result = await response.json();\n";
|
||
$script .= " return result.success ? result.data : null;\n";
|
||
$script .= " } catch (error) {\n";
|
||
$script .= " console.error('Erro na deteção de marca:', error);\n";
|
||
$script .= " return null;\n";
|
||
$script .= " }\n";
|
||
$script .= " }\n\n";
|
||
|
||
// Função de tracking com deteção de marca
|
||
$script .= " async function trackEventWithBrandDetection(eventType, data) {\n";
|
||
$script .= " const currentUrl = window.location.href;\n";
|
||
$script .= " const brandDetection = await detectBrandFromUrl(currentUrl);\n";
|
||
$script .= " \n";
|
||
$script .= " const trackingData = {\n";
|
||
$script .= " event_type: eventType,\n";
|
||
$script .= " campaign_id: config.campaignId,\n";
|
||
$script .= " session_id: getSessionId(),\n";
|
||
$script .= " timestamp: Date.now(),\n";
|
||
$script .= " current_url: currentUrl,\n";
|
||
$script .= " brand_detection: brandDetection,\n";
|
||
$script .= " ...data\n";
|
||
$script .= " };\n\n";
|
||
|
||
$script .= " fetch(config.trackingUrl + '/api/advertising/tracking/' + eventType, {\n";
|
||
$script .= " method: 'POST',\n";
|
||
$script .= " headers: { 'Content-Type': 'application/json' },\n";
|
||
$script .= " body: JSON.stringify(trackingData)\n";
|
||
$script .= " }).catch(console.error);\n";
|
||
$script .= " \n";
|
||
$script .= " // Log deteção de marca para debug\n";
|
||
$script .= " if (brandDetection) {\n";
|
||
$script .= " console.log('Marca detectada:', brandDetection);\n";
|
||
$script .= " }\n";
|
||
$script .= " }\n\n";
|
||
|
||
// Função de tracking (mantida para compatibilidade)
|
||
$script .= " function trackEvent(eventType, data) {\n";
|
||
$script .= " trackEventWithBrandDetection(eventType, data);\n";
|
||
$script .= " }\n\n";
|
||
|
||
// Função para obter session ID
|
||
$script .= " function getSessionId() {\n";
|
||
$script .= " let sessionId = localStorage.getItem('betzoo_session_id');\n";
|
||
$script .= " if (!sessionId) {\n";
|
||
$script .= " sessionId = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);\n";
|
||
$script .= " localStorage.setItem('betzoo_session_id', sessionId);\n";
|
||
$script .= " }\n";
|
||
$script .= " return sessionId;\n";
|
||
$script .= " }\n\n";
|
||
|
||
// Função para criar banner
|
||
$script .= " function createBanner() {\n";
|
||
$script .= " const banner = document.createElement('div');\n";
|
||
$script .= " banner.id = 'betzoo-banner-{$campaign['id']}';\n";
|
||
$script .= " banner.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 9999; background: rgba(0,0,0,0.8); display: flex; align-items: center; justify-content: center;';\n\n";
|
||
|
||
$script .= " const content = document.createElement('div');\n";
|
||
$script .= " content.style.cssText = 'background: white; padding: 20px; border-radius: 8px; max-width: 90%; max-height: 90%; overflow: auto;';\n\n";
|
||
|
||
// Adicionar criativo
|
||
if (!empty($creatives)) {
|
||
$creative = $creatives[0];
|
||
$script .= " const img = document.createElement('img');\n";
|
||
$script .= " img.src = '{$creative['cdn_url']}';\n";
|
||
$script .= " img.alt = '{$creative['alt_text']}';\n";
|
||
$script .= " img.style.cssText = 'max-width: 100%; height: auto; cursor: pointer;';\n";
|
||
$script .= " img.onclick = function() {\n";
|
||
$script .= " trackEventWithBrandDetection('click', { creative_id: {$creative['id']} });\n";
|
||
$script .= " if ('{$creative['click_url']}') {\n";
|
||
$script .= " window.open('{$creative['click_url']}', '_blank');\n";
|
||
$script .= " }\n";
|
||
$script .= " };\n";
|
||
$script .= " content.appendChild(img);\n\n";
|
||
}
|
||
|
||
// Botão de fechar
|
||
$script .= " const closeBtn = document.createElement('button');\n";
|
||
$script .= " closeBtn.textContent = '×';\n";
|
||
$script .= " closeBtn.style.cssText = 'position: absolute; top: 10px; right: 10px; background: none; border: none; font-size: 24px; cursor: pointer; color: #666;';\n";
|
||
$script .= " closeBtn.onclick = function() {\n";
|
||
$script .= " document.body.removeChild(banner);\n";
|
||
$script .= " };\n";
|
||
$script .= " content.appendChild(closeBtn);\n\n";
|
||
|
||
$script .= " banner.appendChild(content);\n";
|
||
$script .= " document.body.appendChild(banner);\n\n";
|
||
|
||
// Track view com deteção de marca
|
||
if (!empty($trackers)) {
|
||
$tracker = $trackers[0];
|
||
$script .= " trackEventWithBrandDetection('view', { tracker_id: {$tracker['id']}, creative_id: " . ($creatives[0]['id'] ?? 0) . " });\n";
|
||
}
|
||
|
||
$script .= " }\n\n";
|
||
|
||
// Auto-executar
|
||
$script .= " // Auto-executar após carregamento\n";
|
||
$script .= " if (document.readyState === 'loading') {\n";
|
||
$script .= " document.addEventListener('DOMContentLoaded', createBanner);\n";
|
||
$script .= " } else {\n";
|
||
$script .= " createBanner();\n";
|
||
$script .= " }\n";
|
||
|
||
$script .= "})();\n";
|
||
|
||
return $script;
|
||
}
|
||
|
||
/**
|
||
* Construir script de popup com deteção configurável de marca
|
||
*/
|
||
private function buildPopupScriptWithBrandDetection(array $campaign, array $formats, array $trackers, array $creatives): string
|
||
{
|
||
// Implementação similar ao banner mas para popup
|
||
return $this->buildBannerScriptWithBrandDetection($campaign, $formats, $trackers, $creatives);
|
||
}
|
||
|
||
/**
|
||
* Construir script native com deteção configurável de marca
|
||
*/
|
||
private function buildNativeScriptWithBrandDetection(array $campaign, array $formats, array $trackers, array $creatives): string
|
||
{
|
||
// Implementação similar ao banner mas para native
|
||
return $this->buildBannerScriptWithBrandDetection($campaign, $formats, $trackers, $creatives);
|
||
}
|
||
|
||
/**
|
||
* Construir script de popup
|
||
*/
|
||
private function buildPopupScript(array $campaign, array $formats, array $trackers, array $creatives): string
|
||
{
|
||
// Similar ao banner mas com comportamento de popup
|
||
return $this->buildBannerScript($campaign, $formats, $trackers, $creatives);
|
||
}
|
||
|
||
/**
|
||
* Construir script nativo
|
||
*/
|
||
private function buildNativeScript(array $campaign, array $formats, array $trackers, array $creatives): string
|
||
{
|
||
$script = "// BetZoo Native Advertising Script - {$campaign['name']}\n";
|
||
$script .= "// Generated: " . date('Y-m-d H:i:s') . "\n\n";
|
||
|
||
$script .= "(function() {\n";
|
||
$script .= " 'use strict';\n\n";
|
||
|
||
// Configurações
|
||
$script .= " const config = {\n";
|
||
$script .= " campaignId: {$campaign['id']},\n";
|
||
$script .= " campaignName: '{$campaign['name']}',\n";
|
||
$script .= " trackingUrl: '" . $this->getTrackingUrl() . "'\n";
|
||
$script .= " };\n\n";
|
||
|
||
// Função de tracking
|
||
$script .= " function trackEvent(eventType, data) {\n";
|
||
$script .= " const trackingData = {\n";
|
||
$script .= " event_type: eventType,\n";
|
||
$script .= " campaign_id: config.campaignId,\n";
|
||
$script .= " session_id: getSessionId(),\n";
|
||
$script .= " timestamp: Date.now(),\n";
|
||
$script .= " ...data\n";
|
||
$script .= " };\n\n";
|
||
|
||
$script .= " fetch(config.trackingUrl + '/api/advertising/tracking/' + eventType, {\n";
|
||
$script .= " method: 'POST',\n";
|
||
$script .= " headers: { 'Content-Type': 'application/json' },\n";
|
||
$script .= " body: JSON.stringify(trackingData)\n";
|
||
$script .= " }).catch(console.error);\n";
|
||
$script .= " }\n\n";
|
||
|
||
// Função para obter session ID
|
||
$script .= " function getSessionId() {\n";
|
||
$script .= " let sessionId = localStorage.getItem('betzoo_session_id');\n";
|
||
$script .= " if (!sessionId) {\n";
|
||
$script .= " sessionId = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);\n";
|
||
$script .= " localStorage.setItem('betzoo_session_id', sessionId);\n";
|
||
$script .= " }\n";
|
||
$script .= " return sessionId;\n";
|
||
$script .= " }\n\n";
|
||
|
||
// Função para inserir anúncio nativo
|
||
$script .= " function insertNativeAd() {\n";
|
||
$script .= " const containers = document.querySelectorAll('.betzoo-native-container');\n";
|
||
$script .= " containers.forEach(function(container, index) {\n";
|
||
$script .= " const ad = document.createElement('div');\n";
|
||
$script .= " ad.className = 'betzoo-native-ad';\n";
|
||
$script .= " ad.innerHTML = '<div style=\"border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 8px; background: #f9f9f9;\">";
|
||
$script .= " <h4 style=\"margin: 0 0 10px 0; color: #333;\">{$campaign['name']}</h4>";
|
||
$script .= " <p style=\"margin: 0 0 15px 0; color: #666;\">Anúncio patrocinado</p>";
|
||
$script .= " <button style=\"background: #007bff; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;\">Ver Mais</button>";
|
||
$script .= " </div>';\n\n";
|
||
|
||
$script .= " ad.querySelector('button').onclick = function() {\n";
|
||
$script .= " trackEvent('click', { position: index });\n";
|
||
$script .= " };\n\n";
|
||
|
||
$script .= " container.appendChild(ad);\n";
|
||
$script .= " trackEvent('view', { position: index });\n";
|
||
$script .= " });\n";
|
||
$script .= " }\n\n";
|
||
|
||
// Auto-executar
|
||
$script .= " if (document.readyState === 'loading') {\n";
|
||
$script .= " document.addEventListener('DOMContentLoaded', insertNativeAd);\n";
|
||
$script .= " } else {\n";
|
||
$script .= " insertNativeAd();\n";
|
||
$script .= " }\n";
|
||
|
||
$script .= "})();\n";
|
||
|
||
return $script;
|
||
}
|
||
|
||
/**
|
||
* Salvar script na base de dados
|
||
*/
|
||
private function saveScript(int $campaignId, string $scriptContent, string $scriptHash): int
|
||
{
|
||
$sql = "INSERT INTO advertising_scripts (
|
||
cuid, campaign_id, name, script_type, script_content, script_hash, version
|
||
) VALUES (
|
||
:cuid, :campaign_id, :name, :script_type, :script_content, :script_hash, :version
|
||
)";
|
||
|
||
$cuid = (string) new \Visus\Cuid2\Cuid2();
|
||
|
||
$this->db->query($sql, [
|
||
':cuid' => $cuid,
|
||
':campaign_id' => $campaignId,
|
||
':name' => 'Script ' . date('Y-m-d H:i:s'),
|
||
':script_type' => 'banner',
|
||
':script_content' => $scriptContent,
|
||
':script_hash' => $scriptHash,
|
||
':version' => '1.0.0'
|
||
]);
|
||
|
||
return $this->db->lastInsertId();
|
||
}
|
||
|
||
/**
|
||
* Salvar ficheiro de script
|
||
*/
|
||
private function saveScriptFile(int $scriptId, string $scriptContent): string
|
||
{
|
||
$fileName = "script_{$scriptId}.js";
|
||
$filePath = $this->outputPath . $fileName;
|
||
|
||
file_put_contents($filePath, $scriptContent);
|
||
|
||
// Atualizar caminho do ficheiro na base de dados
|
||
$sql = "UPDATE advertising_scripts SET file_path = :file_path WHERE id = :id";
|
||
$this->db->query($sql, [
|
||
':file_path' => $filePath,
|
||
':id' => $scriptId
|
||
]);
|
||
|
||
return $fileName;
|
||
}
|
||
|
||
/**
|
||
* Obter URL de tracking
|
||
*/
|
||
private function getTrackingUrl(): string
|
||
{
|
||
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
|
||
$host = $_SERVER['HTTP_HOST'] ?? 'localhost:8888';
|
||
return "{$protocol}://{$host}";
|
||
}
|
||
|
||
/**
|
||
* Deploy de script para CDN
|
||
*/
|
||
public function deployScript(int $scriptId): array
|
||
{
|
||
try {
|
||
// Obter script da base de dados
|
||
$sql = "SELECT * FROM advertising_scripts WHERE id = :id";
|
||
$script = $this->db->fetch($sql, [':id' => $scriptId]);
|
||
|
||
if (!$script) {
|
||
throw new \Exception('Script não encontrado');
|
||
}
|
||
|
||
// Implementar upload para CDN (Cloudflare/S3)
|
||
$cdnUrl = $this->uploadToCDN($script['file_path'], $script['script_content']);
|
||
|
||
// Atualizar URL do CDN na base de dados
|
||
$sql = "UPDATE advertising_scripts SET cdn_url = :cdn_url WHERE id = :id";
|
||
$this->db->query($sql, [
|
||
':cdn_url' => $cdnUrl,
|
||
':id' => $scriptId
|
||
]);
|
||
|
||
return [
|
||
'success' => true,
|
||
'cdn_url' => $cdnUrl,
|
||
'message' => 'Script deployed successfully'
|
||
];
|
||
|
||
} catch (\Exception $e) {
|
||
error_log("Erro ao fazer deploy do script: " . $e->getMessage());
|
||
return [
|
||
'success' => false,
|
||
'error' => $e->getMessage()
|
||
];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Upload de script para CDN
|
||
*/
|
||
private function uploadToCDN(string $filePath, string $scriptContent): string
|
||
{
|
||
try {
|
||
// Verificar se temos configuração de CDN
|
||
$cdnConfig = $this->getCDNConfig();
|
||
|
||
if (!$cdnConfig['enabled']) {
|
||
// Fallback para URL local
|
||
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
|
||
$host = $_SERVER['HTTP_HOST'] ?? 'localhost:8888';
|
||
return "{$protocol}://{$host}/scripts/" . basename($filePath);
|
||
}
|
||
|
||
// Gerar nome único para o ficheiro
|
||
$fileName = 'script_' . md5($scriptContent) . '_' . time() . '.js';
|
||
|
||
// Upload baseado no tipo de CDN configurado
|
||
switch ($cdnConfig['type']) {
|
||
case 'cloudflare':
|
||
return $this->uploadToCloudflare($fileName, $scriptContent, $cdnConfig);
|
||
|
||
case 's3':
|
||
return $this->uploadToS3($fileName, $scriptContent, $cdnConfig);
|
||
|
||
case 'local':
|
||
default:
|
||
return $this->uploadToLocal($fileName, $scriptContent);
|
||
}
|
||
|
||
} catch (\Exception $e) {
|
||
error_log("Erro no upload para CDN: " . $e->getMessage());
|
||
// Fallback para URL local
|
||
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
|
||
$host = $_SERVER['HTTP_HOST'] ?? 'localhost:8888';
|
||
return "{$protocol}://{$host}/scripts/" . basename($filePath);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Obter configuração de CDN
|
||
*/
|
||
private function getCDNConfig(): array
|
||
{
|
||
// Por agora, usar configuração local
|
||
// TODO: Implementar configuração via base de dados ou ficheiro de config
|
||
return [
|
||
'enabled' => false, // Desabilitado por padrão
|
||
'type' => 'local',
|
||
'cloudflare' => [
|
||
'zone_id' => '',
|
||
'api_token' => ''
|
||
],
|
||
's3' => [
|
||
'bucket' => '',
|
||
'region' => '',
|
||
'access_key' => '',
|
||
'secret_key' => ''
|
||
]
|
||
];
|
||
}
|
||
|
||
/**
|
||
* Upload para Cloudflare
|
||
*/
|
||
private function uploadToCloudflare(string $fileName, string $content, array $config): string
|
||
{
|
||
// Implementação básica para Cloudflare
|
||
$url = "https://api.cloudflare.com/client/v4/zones/{$config['cloudflare']['zone_id']}/purge_cache";
|
||
|
||
// Por agora, retornar URL simulada
|
||
return "https://cdn.betzoo.app/scripts/{$fileName}";
|
||
}
|
||
|
||
/**
|
||
* Upload para S3
|
||
*/
|
||
private function uploadToS3(string $fileName, string $content, array $config): string
|
||
{
|
||
// Implementação básica para S3
|
||
// Por agora, retornar URL simulada
|
||
return "https://s3.amazonaws.com/{$config['s3']['bucket']}/scripts/{$fileName}";
|
||
}
|
||
|
||
/**
|
||
* Upload para servidor local
|
||
*/
|
||
private function uploadToLocal(string $fileName, string $content): string
|
||
{
|
||
$localPath = $this->outputPath . $fileName;
|
||
file_put_contents($localPath, $content);
|
||
|
||
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
|
||
$host = $_SERVER['HTTP_HOST'] ?? 'localhost:8888';
|
||
|
||
return "{$protocol}://{$host}/scripts/{$fileName}";
|
||
}
|
||
}
|