+ Coming Soon
+Get notified when we launch
+Don't worry we will not spam you 😊
+diff --git a/cookies.txt b/cookies.txt new file mode 100644 index 0000000..0d6812a --- /dev/null +++ b/cookies.txt @@ -0,0 +1,5 @@ +# Netscape HTTP Cookie File +# https://curl.se/docs/http-cookies.html +# This file was generated by libcurl! Edit at your own risk. + +redirect.moneyflix.com FALSE / FALSE 0 PHPSESSID 8f75ad7bbb4022f56783efc274588ea6 diff --git a/crm/Config/branding.php b/crm/Config/branding.php index 7d927b8..dd749a7 100644 --- a/crm/Config/branding.php +++ b/crm/Config/branding.php @@ -2,37 +2,14 @@ declare(strict_types=1); // app/Config/branding.php +// Configuração exclusiva para MoneyFlix 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. + * Configuração única para MoneyFlix + * Este projeto é exclusivamente para o cliente MoneyFlix */ - - // 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' => [ + 'default' => [ 'client_id' => 'moneyflix', 'company_name' => 'MoneyFlix', 'logo_url' => '/assets/images/moneyflix-dark.png', @@ -54,52 +31,5 @@ return [ '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' - ] ] ]; \ No newline at end of file diff --git a/crm/Core/AuthMiddleware.php b/crm/Core/AuthMiddleware.php index c07ccb0..fc32c28 100644 --- a/crm/Core/AuthMiddleware.php +++ b/crm/Core/AuthMiddleware.php @@ -17,6 +17,29 @@ class AuthMiddleware } } + /** + * API or Auth: allow if logged in OR if Authorization Bearer matches env key + */ + public static function apiOrAuth(): void + { + if (Auth::check()) { + return; + } + $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; + $token = null; + if (stripos($authHeader, 'Bearer ') === 0) { + $token = trim(substr($authHeader, 7)); + } + $expected = $_ENV['REDIRECTS_API_KEY'] ?? getenv('REDIRECTS_API_KEY') ?? ''; + if ($expected && $token && hash_equals($expected, $token)) { + return; + } + http_response_code(401); + header('Content-Type: application/json'); + echo json_encode(['success' => false, 'message' => 'Unauthorized']); + exit; + } + /** * Check if user has a specific role. */ diff --git a/crm/Core/Database/MigrationManager.php b/crm/Core/Database/MigrationManager.php index dc3ff2e..db9d041 100644 --- a/crm/Core/Database/MigrationManager.php +++ b/crm/Core/Database/MigrationManager.php @@ -296,9 +296,11 @@ class MigrationManager private function getLastBatchMigrations(int $steps = 1): array { try { + // Sanitize steps to prevent SQL injection + $steps = max(1, min(100, (int)$steps)); + $result = $this->db->fetchAll( - "SELECT migration FROM migrations ORDER BY batch DESC, executed_at DESC LIMIT ?", - [$steps] + "SELECT migration FROM migrations ORDER BY batch DESC, executed_at DESC LIMIT " . $steps ); return array_column($result, 'migration'); } catch (\Exception $e) { diff --git a/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php b/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php new file mode 100644 index 0000000..fdee6f8 --- /dev/null +++ b/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php @@ -0,0 +1,33 @@ +addColumn('redirect_stats', 'raw_request', 'LONGTEXT NULL COMMENT "Raw request payload (headers, query, meta)"'); + } + + public function down(): void + { + $this->dropColumn('redirect_stats', 'raw_request'); + } +} + + + + + + + + + + diff --git a/crm/Core/InputSanitizer.php b/crm/Core/InputSanitizer.php index af22810..02272b8 100644 --- a/crm/Core/InputSanitizer.php +++ b/crm/Core/InputSanitizer.php @@ -157,4 +157,17 @@ class InputSanitizer self::$sanitizedInputs = []; self::$initialized = false; } + /** + * Converte vários formatos para boolean seguro + */ + public static function toBoolean($value, bool $default = false): bool + { + if ($value === null || $value === '') return $default; + if (is_bool($value)) return $value; + if (is_int($value)) return $value === 1; + $normalized = strtolower(trim((string)$value)); + if (in_array($normalized, ['1','true','on','yes'], true)) return true; + if (in_array($normalized, ['0','false','off','no'], true)) return false; + return $default; + } } \ No newline at end of file diff --git a/crm/Core/PathManager.php b/crm/Core/PathManager.php index cc3f296..a86d9d2 100644 --- a/crm/Core/PathManager.php +++ b/crm/Core/PathManager.php @@ -30,7 +30,15 @@ class PathManager self::$rootPath = self::findRootPath(); // Define all other paths relative to root - self::$appPath = self::$rootPath . '/app'; + // Check if we're in the crm structure or app structure + if (is_dir(self::$rootPath . '/crm')) { + // CRM structure: root/crm/ + self::$appPath = self::$rootPath . '/crm'; + } else { + // App structure: root/app/ + self::$appPath = self::$rootPath . '/app'; + } + self::$modulesPath = self::$appPath . '/Modules'; self::$storagePath = self::$rootPath . '/storage'; self::$publicPath = self::$rootPath . '/public'; @@ -46,11 +54,13 @@ class PathManager */ private static function findRootPath(): string { + // Force root path to be the directory containing the app folder + // This fixes the issue where composer.json exists in both root and app directories $currentPath = __DIR__; - // Go up directories until we find composer.json + // Go up directories until we find the directory that contains both composer.json and app folder while ($currentPath !== '/' && $currentPath !== '') { - if (file_exists($currentPath . '/composer.json')) { + if (file_exists($currentPath . '/composer.json') && is_dir($currentPath . '/app')) { return $currentPath; } $currentPath = dirname($currentPath); diff --git a/crm/Core/Validate.php b/crm/Core/Validate.php index 677c1b2..b720c48 100644 --- a/crm/Core/Validate.php +++ b/crm/Core/Validate.php @@ -208,7 +208,20 @@ class Validate */ public static function boolean($value): bool { - return is_bool($value) || in_array($value, [0, 1, '0', '1', true, false], true); + // Permitir nulo/vazio quando usado com 'nullable' + if ($value === null || $value === '') return true; + if (is_bool($value)) return true; + // Aceitar valores comuns de formulários web + if (is_string($value)) { + $normalized = strtolower(trim($value)); + if (in_array($normalized, ['1','0','true','false','on','off','yes','no'], true)) { + return true; + } + } + if (is_int($value)) { + return in_array($value, [0,1], true); + } + return in_array($value, ['0','1', 0, 1, true, false], true); } /** diff --git a/crm/Core/Validator.php b/crm/Core/Validator.php index b40757d..2fa79a4 100644 --- a/crm/Core/Validator.php +++ b/crm/Core/Validator.php @@ -248,8 +248,8 @@ class Validator $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.", + 'min' => "O campo {$fieldName} deve ter pelo menos " . (isset($params[0]) ? $params[0] : '0') . " caracteres.", + 'max' => "O campo {$fieldName} deve ter no máximo " . (isset($params[0]) ? $params[0] : '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.", @@ -258,21 +258,21 @@ class Validator '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), + 'in' => "O campo {$fieldName} deve ser um dos valores: " . (empty($params) ? '' : implode(', ', $params)), + 'not_in' => "O campo {$fieldName} não pode ser um dos valores: " . (empty($params) ? '' : 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]}.", + 'different' => "O campo {$fieldName} deve ser diferente de " . (isset($params[0]) ? $params[0] : 'outro campo') . ".", + 'same' => "O campo {$fieldName} deve ser igual a " . (isset($params[0]) ? $params[0] : 'outro campo') . ".", '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]}.", + 'mimes' => "O campo {$fieldName} deve ser um arquivo do tipo: " . (empty($params) ? '' : implode(', ', $params)), + 'size' => "O campo {$fieldName} deve ter no máximo " . (isset($params[0]) ? $params[0] : '0') . " KB.", + 'between' => "O campo {$fieldName} deve estar entre " . (isset($params[0]) ? $params[0] : '0') . " e " . (isset($params[1]) ? $params[1] : '0') . ".", + 'min_value' => "O campo {$fieldName} deve ser pelo menos " . (isset($params[0]) ? $params[0] : '0') . ".", + 'max_value' => "O campo {$fieldName} deve ser no máximo " . (isset($params[0]) ? $params[0] : '0') . ".", 'strong_password' => "O campo {$fieldName} deve ter pelo menos 8 caracteres, incluindo maiúscula, minúscula e número." ]; diff --git a/crm/Modules/Controllers/PagesController.php b/crm/Modules/Controllers/PagesController.php new file mode 100644 index 0000000..e398766 --- /dev/null +++ b/crm/Modules/Controllers/PagesController.php @@ -0,0 +1,400 @@ + 'Starter Page', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Starter' + ]); + // A página starter é uma tela em branco por design. + // Não há mais nada a renderizar aqui para evitar o ciclo. + } + ]); + } + + public static function profile(): void + { + try { + // Get current user ID from session + $userId = \App\Core\Auth::id(); + if (!$userId) { + header('Location: /auth/login'); + exit; + } + + // Load user data from database (fallback if Users module not available) + $userData = null; + if (class_exists('\\App\\Modules\\Users\\Models\\UserModel')) { + $userModel = new \App\Modules\Users\Models\UserModel(); + $userData = $userModel->find($userId); + } else { + // Fallback: create basic user data from Auth + $authUser = Auth::user(); + $userData = $authUser ?: [ + 'first_name' => 'User', + 'last_name' => 'Name', + 'email' => 'user@example.com', + 'username' => 'user', + 'job_title' => '', + 'company_name' => '', + 'city' => '', + 'country' => '', + 'phone' => '', + 'website' => '', + 'avatar' => '/assets/images/users/avatar-1.jpg', + 'profile_bg' => '/assets/images/small/img-4.jpg', + 'created_at' => date('Y-m-d H:i:s'), + 'followers_count' => 0, + 'following_count' => 0, + 'bio' => 'No bio available.', + 'location' => 'N/A', + 'skills' => '[]', + 'social_links' => '{}', + 'profile_completion' => 50 + ]; + } + + if (!$userData) { + throw new \Exception('User not found'); + } + + // Prepare user data + $user = [ + 'id' => $userId, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'job_title' => Sanitize::string($userData['job_title'] ?? ''), + 'company_name' => Sanitize::string($userData['company_name'] ?? ''), + 'city' => Sanitize::string($userData['city'] ?? ''), + 'country' => Sanitize::string($userData['country'] ?? ''), + 'phone' => Sanitize::string($userData['phone'] ?? ''), + 'website' => Sanitize::url($userData['website'] ?? ''), + 'avatar' => Sanitize::string($userData['avatar'] ?? '/assets/images/users/avatar-1.jpg'), + 'profile_bg' => Sanitize::string($userData['profile_bg'] ?? '/assets/images/small/img-4.jpg'), + 'created_at' => $userData['created_at'] ?? '', + 'followers_count' => $userData['followers_count'] ?? 0, + 'following_count' => $userData['following_count'] ?? 0 + ]; + + // Load profile data from database + $profile = [ + 'bio' => Sanitize::string($userData['bio'] ?? 'No bio available.'), + 'location' => Sanitize::string($userData['location'] ?? 'N/A'), + 'skills' => json_decode($userData['skills'] ?? '[]', true) ?: [], + 'social_links' => json_decode($userData['social_links'] ?? '{}', true) ?: [], + 'profile_completion' => $userData['profile_completion'] ?? 50 + ]; + + // Load recent activities from database (with fallback) + $db = \App\Core\DatabaseManager::getInstance(); + $recentActivities = []; + $recentProjects = []; + $recentDocuments = []; + + try { + $recentActivities = $db->fetchAll(" + SELECT + a.id, + a.activity_type, + a.description, + a.created_at, + u.first_name, + u.last_name, + u.avatar + FROM user_activities a + LEFT JOIN users u ON a.user_id = u.id + WHERE a.user_id = ? OR a.target_user_id = ? + ORDER BY a.created_at DESC + LIMIT 10 + ", [$userId, $userId]) ?: []; + } catch (\Exception $e) { + // Table might not exist, use empty array + } + + try { + $recentProjects = $db->fetchAll(" + SELECT + p.id, + p.name, + p.description, + p.status, + p.created_at, + p.updated_at + FROM projects p + WHERE p.user_id = ? + ORDER BY p.updated_at DESC + LIMIT 5 + ", [$userId]) ?: []; + } catch (\Exception $e) { + // Table might not exist, use empty array + } + + try { + $recentDocuments = $db->fetchAll(" + SELECT + d.id, + d.filename, + d.file_type, + d.file_size, + d.uploaded_at + FROM user_documents d + WHERE d.user_id = ? + ORDER BY d.uploaded_at DESC + LIMIT 10 + ", [$userId]) ?: []; + } catch (\Exception $e) { + // Table might not exist, use empty array + } + + View::render('layouts/main.php', [ + 'title' => 'Profile', + 'page_content' => function() use ($user, $profile, $recentActivities, $recentProjects, $recentDocuments) { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Profile' + ]); + View::render('@pages/profile', [ + 'user' => $user, + 'profile' => $profile, + 'recentActivities' => $recentActivities, + 'recentProjects' => $recentProjects, + 'recentDocuments' => $recentDocuments + ]); + } + ]); + } catch (\Exception $e) { + \App\Core\ErrorReporter::report($e, ['context' => 'pages_profile', 'user_id' => $userId ?? 0]); + + if (strpos($e->getMessage(), 'Authentication required') !== false) { + header('Location: /auth/login'); + exit; + } else { + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + } + + public static function team(): void + { + View::render('layouts/main.php', [ + 'title' => 'Team', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Team' + ]); + View::render('@pages/team'); + } + ]); + } + + public static function timeline(): void + { + View::render('layouts/main.php', [ + 'title' => 'Timeline', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Timeline' + ]); + View::render('@pages/timeline'); + } + ]); + } + + public static function faqs(): void + { + View::render('layouts/main.php', [ + 'title' => 'FAQs', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'FAQs' + ]); + View::render('@pages/faqs'); + } + ]); + } + + public static function pricing(): void + { + View::render('layouts/main.php', [ + 'title' => 'Pricing', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Pricing' + ]); + View::render('@pages/pricing'); + } + ]); + } + + public static function gallery(): void + { + View::render('layouts/main.php', [ + 'title' => 'Gallery', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Gallery' + ]); + View::render('@pages/gallery'); + } + ]); + } + + public static function maintenance(): void + { + View::render('layouts/main.php', [ + 'title' => 'Maintenance', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Maintenance' + ]); + View::render('@pages/maintenance'); + } + ]); + } + + public static function comingSoon(): void + { + View::render('layouts/main.php', [ + 'title' => 'Coming Soon', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Coming Soon' + ]); + View::render('@pages/coming/soon'); + } + ]); + } + + public static function sitemap(): void + { + View::render('layouts/main.php', [ + 'title' => 'Sitemap', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Sitemap' + ]); + View::render('@pages/sitemap'); + } + ]); + } + + public static function searchResults(): void + { + View::render('layouts/main.php', [ + 'title' => 'Search Results', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Search Results' + ]); + View::render('@pages/search/results'); + } + ]); + } + + public static function privacyPolicy(): void + { + View::render('layouts/main.php', [ + 'title' => 'Privacy Policy', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Privacy Policy' + ]); + View::render('@pages/privacy/policy'); + } + ]); + } + + public static function termsOfService(): void + { + View::render('layouts/main.php', [ + 'title' => 'Terms of Service', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Terms of Service' + ]); + View::render('@pages/term/conditions'); + } + ]); + } + + public static function pagesProfileSettingsPage(): void + { + View::render('layouts/main.php', [ + 'title' => 'Profile Settings', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Profile Settings' + ]); + View::render('@pages/profile/settings'); + } + ]); + } + + public static function pagesBlogOverviewPage(): void + { + View::render('layouts/main.php', [ + 'title' => 'Blog Overview', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Blog Overview' + ]); + View::render('@pages/blog/overview'); + } + ]); + } + + public static function pagesBlogGridPage(): void + { + View::render('layouts/main.php', [ + 'title' => 'Blog Grid', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Blog Grid' + ]); + View::render('@pages/blog/grid'); + } + ]); + } + + public static function pagesBlogListPage(): void + { + View::render('layouts/main.php', [ + 'title' => 'Blog List', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Pages', + 'title' => 'Blog List' + ]); + View::render('@pages/blog/list'); + } + ]); + } +} diff --git a/crm/Modules/Controllers/PublicCampaignsController.php b/crm/Modules/Controllers/PublicCampaignsController.php new file mode 100644 index 0000000..bc19417 --- /dev/null +++ b/crm/Modules/Controllers/PublicCampaignsController.php @@ -0,0 +1,444 @@ +db = DatabaseManager::getInstance(); + } + + /** + * Renders the public campaign analytics page. + */ + public function analytics(string $slug): void + { + if (empty($slug)) { + http_response_code(404); + echo "Campaign slug is required."; + return; + } + + $branding = Branding::get(); + $page_title = ($branding['company_name'] ?? 'Analytics') . ' - Campaign Dashboard'; + + View::render('layouts/public-blank.php', [ + 'title' => $page_title, + 'page_name' => 'public-campaign-analytics', + 'branding' => $branding, + 'slug' => $slug, + 'page_content' => function() use ($branding, $slug) { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Campaign Analytics', + 'title' => 'Campaign Performance' + ]); + View::render('@modules/public-campaign-analytics', [ + 'branding' => $branding, + 'slug' => $slug + ]); + } + ]); + } + + /** + * API endpoint: Get campaign stats by slug and optional filters. + */ + public function getCampaignStats(string $slug): void + { + header('Content-Type: application/json'); + if (empty($slug)) { + http_response_code(400); + echo json_encode(['success' => false, 'message' => 'Missing campaign slug']); + return; + } + + // Get query parameters + $startDate = $_GET['startDate'] ?? date('Y-m-d', strtotime('-30 days')); + $endDate = $_GET['endDate'] ?? date('Y-m-d'); + $domain = $_GET['domain'] ?? ''; + + try { + // Buscar campanha por cuid (slug) + $campaign = $this->getCampaignByCuid($slug); + if (!$campaign) { + http_response_code(404); + echo json_encode(['success' => false, 'message' => 'Campaign not found']); + return; + } + + // Buscar dados reais da campanha + $data = $this->getRealCampaignData($campaign['id'], $startDate, $endDate, $domain); + + echo json_encode(['success' => true, 'data' => $data]); + + } catch (\Exception $e) { + http_response_code(500); + echo json_encode(['success' => false, 'message' => 'Error fetching campaign data']); + } + } + + /** + * Get campaign by cuid (slug) + */ + private function getCampaignByCuid(string $cuid): ?array + { + $sql = "SELECT + c.id AS campaign_id, + c.name AS campaign_name, + c.description AS campaign_description, + c.cuid AS campaign_cuid, + c.status AS campaign_status, + c.budget AS campaign_budget, + c.start_date AS start_date, + c.end_date AS end_date, + c.site_group_id AS site_group_id, + c.created_at AS created_date, + c.updated_at AS updated_date + FROM + advertising_campaigns c + WHERE + c.cuid = :cuid AND c.status >= 0"; + return $this->db->fetch($sql, [':cuid' => $cuid]); + } + + /** + * Get real campaign data from database + */ + private function getRealCampaignData(int $campaignId, string $startDate, string $endDate, string $domain): array + { + // Buscar formatos da campanha + $formats = $this->getCampaignFormats($campaignId); + + // Buscar estatísticas reais + $stats = $this->getCampaignStatsData($campaignId, $startDate, $endDate); + + // Buscar dados de gráficos + $charts = $this->getCampaignCharts($campaignId, $startDate, $endDate); + + // Buscar dados de tabelas + $tables = $this->getCampaignTables($campaignId, $startDate, $endDate); + + // Buscar domínios disponíveis + $domains = $this->getAvailableDomains($campaignId); + + return [ + 'slug' => $campaignId, + 'filters' => [ + 'domains' => $domains + ], + 'scriptInfo' => [ + 'estimatedRevenue' => $stats['total_revenue'] ?? 0, + 'scriptStatusClass' => $this->getStatusClass($stats['status'] ?? 'active'), + 'scriptStatusDisplay' => $this->getStatusDisplay($stats['status'] ?? 'active'), + 'totalViewsAllTime' => $stats['total_views'] ?? 0, + 'firstHit' => $stats['first_hit'] ?? date('Y-m-d'), + 'dealType' => 'CPM', + 'scriptId' => 'script_' . $campaignId + ], + 'kpis' => [ + 'impressions' => ['value' => $stats['total_views'] ?? 0], + 'clicks' => ['value' => $stats['total_clicks'] ?? 0], + 'ctr' => ['value' => $stats['avg_ctr'] ?? 0] + ], + 'charts' => $charts, + 'tables' => $tables + ]; + } + + /** + * Get campaign formats + */ + private function getCampaignFormats(int $campaignId): array + { + $sql = "SELECT + f.id AS format_id, + f.name AS format_name, + f.type AS format_type, + f.width AS format_width, + f.height AS format_height, + f.weight AS format_weight, + f.is_active AS is_active, + f.campaign_id AS campaign_id, + f.settings AS format_settings, + f.created_at AS created_date, + f.updated_at AS updated_date + FROM + advertising_formats f + WHERE + f.campaign_id = :campaign_id AND f.is_active = 1"; + return $this->db->fetchAll($sql, [':campaign_id' => $campaignId]) ?: []; + } + + /** + * Get campaign statistics data + */ + private function getCampaignStatsData(int $campaignId, string $startDate, string $endDate): array + { + $sql = "SELECT + c.id, + c.name, + c.status, + COUNT(DISTINCT f.id) as formats_count, + COUNT(DISTINCT cr.id) as creatives_count, + SUM(r.views) as total_views, + SUM(r.clicks) as total_clicks, + SUM(r.registers) as total_registers, + SUM(r.revenue) as total_revenue, + AVG(r.ctr) as avg_ctr, + AVG(r.cpm) as avg_cpm, + AVG(r.epc) as avg_epc, + MIN(r.date) as first_hit + FROM advertising_campaigns c + LEFT JOIN advertising_formats f ON c.id = f.campaign_id + LEFT JOIN advertising_creatives cr ON f.id = cr.format_id + LEFT JOIN advertising_reports_daily r ON c.id = r.campaign_id + WHERE c.id = :campaign_id AND c.status >= 0"; + + $params = [':campaign_id' => $campaignId]; + + if ($startDate) { + $sql .= " AND r.date >= :start_date"; + $params[':start_date'] = $startDate; + } + + if ($endDate) { + $sql .= " AND r.date <= :end_date"; + $params[':end_date'] = $endDate; + } + + $sql .= " GROUP BY c.id"; + + return $this->db->fetch($sql, $params) ?: []; + } + + /** + * Get campaign charts data + */ + private function getCampaignCharts(int $campaignId, string $startDate, string $endDate): array + { + // Dados de impressions e clicks por dia + $impressionsClicks = $this->getImpressionsClicksData($campaignId, $startDate, $endDate); + + // Dados geográficos + $geos = $this->getGeosData($campaignId, $startDate, $endDate); + + // Dados de dispositivos + $devices = $this->getDevicesData($campaignId, $startDate, $endDate); + + return [ + 'impressionsAndClicks' => $impressionsClicks, + 'geos' => $geos, + 'devices' => $devices + ]; + } + + /** + * Get impressions and clicks data for charts + */ + private function getImpressionsClicksData(int $campaignId, string $startDate, string $endDate): array + { + $sql = "SELECT + DATE(r.date) as date, + SUM(r.views) as impressions, + SUM(r.clicks) as clicks + FROM advertising_reports_daily r + WHERE r.campaign_id = :campaign_id + AND r.date BETWEEN :start_date AND :end_date + GROUP BY DATE(r.date) + ORDER BY r.date"; + + $result = $this->db->fetchAll($sql, [ + ':campaign_id' => $campaignId, + ':start_date' => $startDate, + ':end_date' => $endDate + ]) ?: []; + + $categories = []; + $impressionsData = []; + $clicksData = []; + + foreach ($result as $row) { + $categories[] = $row['date']; + $impressionsData[] = (int)$row['impressions']; + $clicksData[] = (int)$row['clicks']; + } + + return [ + 'series' => [ + ['name' => 'Impressions', 'data' => $impressionsData], + ['name' => 'Clicks', 'data' => $clicksData] + ], + 'categories' => $categories + ]; + } + + /** + * Get geographical data for charts + */ + private function getGeosData(int $campaignId, string $startDate, string $endDate): array + { + $sql = "SELECT + r.country_code, + SUM(r.views) as impressions + FROM advertising_reports_daily r + WHERE r.campaign_id = :campaign_id + AND r.date BETWEEN :start_date AND :end_date + AND r.country_code IS NOT NULL + GROUP BY r.country_code + ORDER BY impressions DESC + LIMIT 10"; + + $result = $this->db->fetchAll($sql, [ + ':campaign_id' => $campaignId, + ':start_date' => $startDate, + ':end_date' => $endDate + ]) ?: []; + + $series = []; + $labels = []; + + foreach ($result as $row) { + $labels[] = $row['country_code']; + $series[] = (int)$row['impressions']; + } + + return [ + 'series' => $series, + 'labels' => $labels + ]; + } + + /** + * Get devices data for charts + */ + private function getDevicesData(int $campaignId, string $startDate, string $endDate): array + { + $sql = "SELECT + r.device_type, + SUM(r.views) as impressions + FROM advertising_reports_daily r + WHERE r.campaign_id = :campaign_id + AND r.date BETWEEN :start_date AND :end_date + AND r.device_type IS NOT NULL + GROUP BY r.device_type + ORDER BY impressions DESC"; + + $result = $this->db->fetchAll($sql, [ + ':campaign_id' => $campaignId, + ':start_date' => $startDate, + ':end_date' => $endDate + ]) ?: []; + + $series = []; + $labels = []; + + foreach ($result as $row) { + $labels[] = ucfirst($row['device_type']); + $series[] = (int)$row['impressions']; + } + + return [ + 'series' => $series, + 'labels' => $labels + ]; + } + + /** + * Get campaign tables data + */ + private function getCampaignTables(int $campaignId, string $startDate, string $endDate): array + { + $sql = "SELECT + r.date, + r.country_code, + r.views, + r.clicks, + r.ctr + FROM advertising_reports_daily r + WHERE r.campaign_id = :campaign_id + AND r.date BETWEEN :start_date AND :end_date + ORDER BY r.date DESC, r.views DESC + LIMIT 20"; + + $result = $this->db->fetchAll($sql, [ + ':campaign_id' => $campaignId, + ':start_date' => $startDate, + ':end_date' => $endDate + ]) ?: []; + + $dailyStats = []; + foreach ($result as $row) { + $dailyStats[] = [ + $row['date'], + $row['country_code'] ?? 'Unknown', + number_format($row['views']), + number_format($row['clicks']), + number_format($row['ctr'], 2) . '%' + ]; + } + + return [ + 'dailyStats' => $dailyStats + ]; + } + + /** + * Get available domains for the campaign + */ + private function getAvailableDomains(int $campaignId): array + { + try { + // Buscar domínios reais das campanhas + $domains = $this->db->fetchAll("SELECT DISTINCT + domain + FROM advertising_campaigns + WHERE domain IS NOT NULL AND domain != '' AND deleted_at IS NULL + ORDER BY domain"); + + if (empty($domains)) { + return ['performix.pt', 'bitreport.pt', 'crm.local']; + } + + return array_column($domains, 'domain'); + + } catch (\Exception $e) { + return ['performix.pt', 'bitreport.pt', 'crm.local']; + } + } + + /** + * Get status class for display + */ + private function getStatusClass(string $status): string + { + return match($status) { + 'active' => 'badge bg-success-subtle text-success', + 'paused' => 'badge bg-warning-subtle text-warning', + 'completed' => 'badge bg-info-subtle text-info', + 'archived' => 'badge bg-secondary-subtle text-secondary', + default => 'badge bg-secondary-subtle text-secondary' + }; + } + + /** + * Get status display text + */ + private function getStatusDisplay(string $status): string + { + return match($status) { + 'active' => 'Ativo', + 'paused' => 'Pausado', + 'completed' => 'Concluído', + 'archived' => 'Arquivado', + default => 'Desconhecido' + }; + } +} diff --git a/crm/Modules/Routes/public.php b/crm/Modules/Routes/public.php new file mode 100644 index 0000000..1320e56 --- /dev/null +++ b/crm/Modules/Routes/public.php @@ -0,0 +1,6 @@ +get('/public/analytics/{slug}', [PublicCampaignsController::class, 'analytics']); +$router->get('/api/campaigns/{slug}', [PublicCampaignsController::class, 'getCampaignStats']); diff --git a/crm/Modules/Routes/web.php b/crm/Modules/Routes/web.php new file mode 100644 index 0000000..d31dabc --- /dev/null +++ b/crm/Modules/Routes/web.php @@ -0,0 +1,21 @@ +get('/apps/pages/starter', [PagesController::class, 'starter']); +$router->get('/apps/pages/profile', [PagesController::class, 'profile']); +$router->get('/apps/pages/profile-settings/', [PagesController::class, 'pagesProfileSettingsPage']); +$router->get('/apps/pages/team', [PagesController::class, 'team']); +$router->get('/apps/pages/timeline', [PagesController::class, 'timeline']); +$router->get('/apps/pages/faqs', [PagesController::class, 'faqs']); +$router->get('/apps/pages/pricing', [PagesController::class, 'pricing']); +$router->get('/apps/pages/gallery', [PagesController::class, 'gallery']); +$router->get('/apps/pages/maintenance', [PagesController::class, 'maintenance']); +$router->get('/apps/pages/coming-soon', [PagesController::class, 'comingSoon']); +$router->get('/apps/pages/sitemap', [PagesController::class, 'sitemap']); +$router->get('/apps/pages/search/results', [PagesController::class, 'searchResults']); +$router->get('/apps/pages/privacy-policy', [PagesController::class, 'privacyPolicy']); +$router->get('/apps/pages/terms-of-service', [PagesController::class, 'termsOfService']); diff --git a/crm/Modules/Views/404.php b/crm/Modules/Views/404.php new file mode 100644 index 0000000..99b2959 --- /dev/null +++ b/crm/Modules/Views/404.php @@ -0,0 +1,16 @@ + 'Erro 404 - Página não encontrada', + 'page_content' => function() { + // Simple, styled 404 message (Portuguese) + echo '
';
+ echo 'A página que procura não existe ou foi movida.
'; + echo 'Voltar à página inicial'; + echo 'Exploring the beauty of slow living and intentional + growth. Discover tips on mindfulness, wellness, and living a balanced life.
+ Read Post +Empowering the creators A platform for sharing creative + projects, tech solutions, and future-thinking ideas to shape the next + generation.
+ Read Post +Where ideas come to life through words and design. + Exploring the intersection of creativity, technology, and thoughtful living to + fuel your next big idea.
+ Read Post +Curated perspectives on creativity, innovation, and + lifestyle. A blend of expert insights, stories, and tips to inspire personal + growth and creative thinking.
+ Read Post +Crafting a life full of intention Explore ideas on + mindful living, personal development, and how to design a life that truly + inspires you.
+ Read Post +Where thoughtful design meets meaningful storytelling. + Sharing unique viewpoints on creativity, innovation, and the art of crafting a + fulfilling life.
+ Read Post +Designing a life of creativity A space for creators, + dreamers, and innovators to explore ideas and strategies for building a + meaningful life.
+ Read Post +A hub for artists, tech enthusiasts, and creatives + looking to stay ahead of the curve and bring ideas to life ideas, trends, and + inspiration.
+ Read Post +Showing 1 to 8 of 33 entries
+Art & Design
+How to create impactful narratives through visual + elements.
+Storytelling has always been a powerful way to + communicate, and in the world of design, it is no different. Visual + storytelling allows designers to go beyond aesthetics and create + meaningful connections with their audience. It transforms static designs + into engaging narratives that leave a lasting impression. In this post, + we will explore the art of storytelling in design, how it enhances user + experiences, and how you can incorporate it into your creative work.
+Design is more than just making things look + good—it is about conveying a message and creating an experience. And the + best designs tell a story. From logos and branding to websites and + product design, storytelling is woven into every aspect of successful + design projects. When you integrate storytelling into your design, you + give your audience something to connect with emotionally, making your + work more memorable and impactful.
+At its core, storytelling in design helps to + create a deeper emotional connection between the user and the product or + brand. It provides context, helps communicate values, and drives + engagement by making the user feel like they are part of the narrative. + Here are a few reasons why storytelling is a vital part of design:
+++"Storytelling in design turns a simple visual + into an experience. It transforms static elements into living + narratives that engage, inspire, and resonate with those who + interact with them."
+ +
To tell a story through design, you need to + incorporate several key elements:
+I am getting message from customers + that when they place order always get error message . +
+ Reply +Please be sure to check your + Spam mailbox to see if your email filters have + identified the email from Dell as spam.
+ Reply +There are many variations of passages + of Lorem Ipsum available, but the majority have suffered + alteration in some form, by injected humour, or + randomised words which do not look even slightly + believable.
+ Reply +If you are going to use a passage of + Lorem Ipsum, you need to be sure there is not anything + embarrassing hidden in the middle of text.
+ Reply +The standard chunk of Lorem Ipsum used + since the 1500s is reproduced below for those interested. + Sections 1.10.32 and 1.10.33.
+ Reply +
+ Don't worry we will not spam you 😊
+Last update: 16 Sept, 2022
+At Website Name, accessible at Website.com, one of our main priorities is the privacy of our visitors. This Privacy Policy document contains types of information that is collected and recorded by Website Name and how we use it.
+If you have additional questions or require more information about our Privacy Policy, do not hesitate to contact us through email at Email@Website.com
+This privacy policy applies only to our online activities and is valid for visitors to our website with regards to the information that they shared and/or collect in Website Name. This policy is not applicable to any information collected offline or via channels other than this website.
+How we use your information:
+There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable.
+If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet.
+On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment.
+It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
+If you contact us directly, we may receive additional information about you such as your name, email address, phone number, the contents of the message and/or attachments you may send us, and any other information you may choose to provide.
+Communicate with you, either directly or through one of our partners, including for customer service, to provide you with updates and other information relating to the website, and for marketing and promotional purposes.
+When you register for an Account, we may ask for your contact information, including items such as name, company name, address, email address, and telephone number.
+We use the information we collect in various ways, including to:
+Like any other website, Website Name uses ‘cookies'. These cookies are used to store information including visitors' preferences, and the pages on the website that the visitor accessed or visited. The information is used to optimize the users' experience by customizing our web page content based on visitors' browser type and/or other information.
+Some of advertisers on our site may use cookies and web beacons. Our advertising partners are listed below. Each of our advertising partners has their own Privacy Policy for their policies on user data. For easier access, we hyperlinked to their Privacy Policies below.
+Website Name's Privacy Policy does not apply to other advertisers or websites. Thus, we are advising you to consult the respective Privacy Policies of these third-party ad servers for more detailed information. It may include their practices and instructions about how to opt-out of certain options. You may find a complete list of these Privacy Policies and their links here: Privacy Policy Links.
+Followers
+Following
+| Full Name : | ++ |
|---|---|
| Mobile : | ++ |
| E-mail : | ++ |
| Location : | ++ |
| Joining Date | ++ |
Your recent activities will appear here
+Your activities will appear here as you use the system
+Total Impressions
+Total Clicks
+CTR
+Estimated Revenue
+| Date | +Country | +Impressions | +Clicks | +CTR | +
|---|---|---|---|---|
| + | + | + | + | + |
Loading campaign data...
+An error occurred while loading the campaign data.
+Last update: 16 Sept, 2022
+These terms and conditions outline the rules and regulations for the use of Company Name's Website, located at Website.com.
+By accessing this website we assume you accept these terms and conditions. Do not continue to use Website Name if you do not agree to take all of the terms and conditions stated on this page.
+Most interactive websites use cookies to let us retrieve the user's details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.
+Unless otherwise stated, Company Name and/or its licensors own the intellectual property rights for all material on Website Name. All intellectual property rights are reserved. You may access this from Website Name for your own personal use subjected to restrictions set in these terms and conditions.
+You must not:
+This Agreement shall begin on the date hereof.
+Parts of this website offer an opportunity for users to post and exchange opinions and information in certain areas of the website. Company Name does not filter, edit, publish or review Comments prior to their presence on the website. Comments do not reflect the views and opinions of Company Name,its agents and/or affiliates.
+Company Name reserves the right to monitor all Comments and to remove any Comments which can be considered inappropriate, offensive or causes breach of these Terms and Conditions.
+You warrant and represent that:
+You hereby grant Company Name a non-exclusive license to use, reproduce, edit and authorize others to use, reproduce and edit any of your Comments in any and all forms, formats or media.
+Approved organizations may hyperlink to our Website as follows:
+No use of Company Name's logo or other artwork will be allowed for linking absent a trademark license agreement.
+