- Add source maps and license files for compiled assets - Add debug and test files for development - Complete Git repository with all necessary files for MoneyFlix project
667 lines
19 KiB
PHP
667 lines
19 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Core;
|
|
|
|
use App\Core\Auth;
|
|
use App\Core\View;
|
|
use App\Core\ErrorReporter;
|
|
use App\Core\InputSanitizer;
|
|
use App\Core\Validator;
|
|
use App\Core\ServiceContainer;
|
|
use App\Core\ValidatorFactory;
|
|
|
|
/**
|
|
* BaseController - Controller base para todos os controllers
|
|
* Fornece funcionalidades comuns e métodos utilitários
|
|
*/
|
|
abstract class BaseController
|
|
{
|
|
protected array $data = [];
|
|
protected ?Validator $validator = null;
|
|
protected string $moduleName;
|
|
protected ServiceContainer $container;
|
|
|
|
/**
|
|
* Construtor do BaseController
|
|
*/
|
|
public function __construct(string $moduleName = '')
|
|
{
|
|
$this->moduleName = $moduleName;
|
|
$this->container = ServiceContainer::getInstance();
|
|
}
|
|
|
|
/**
|
|
* Resolver um serviço do módulo
|
|
*/
|
|
protected function resolveModuleService(string $serviceName)
|
|
{
|
|
if (empty($this->moduleName)) {
|
|
throw new \InvalidArgumentException('Module name not set in controller');
|
|
}
|
|
|
|
// Tentar resolver como "Module:ServiceName"
|
|
try {
|
|
return $this->container->resolve($this->moduleName . ':' . $serviceName);
|
|
} catch (\InvalidArgumentException $e) {
|
|
// Se falhar, tentar resolver diretamente
|
|
return $this->container->resolve($serviceName);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Resolver um serviço global
|
|
*/
|
|
protected function resolve(string $serviceName)
|
|
{
|
|
return $this->container->resolve($serviceName);
|
|
}
|
|
|
|
/**
|
|
* Renderizar view
|
|
*/
|
|
protected function render(string $view, array $data = []): void
|
|
{
|
|
$this->data = array_merge($this->data, $data);
|
|
View::render($view, $this->data);
|
|
}
|
|
|
|
/**
|
|
* Resposta JSON
|
|
*/
|
|
protected function jsonResponse(array $data, int $statusCode = 200): void
|
|
{
|
|
// Clean any previous output
|
|
if (ob_get_level()) {
|
|
ob_clean();
|
|
}
|
|
|
|
// Only set headers if they haven't been sent yet
|
|
if (!headers_sent()) {
|
|
http_response_code($statusCode);
|
|
header('Content-Type: application/json');
|
|
}
|
|
|
|
echo json_encode($data, JSON_UNESCAPED_UNICODE);
|
|
exit; // Ensure no further output
|
|
}
|
|
|
|
/**
|
|
* Resposta de erro padronizada
|
|
*/
|
|
protected function errorResponse(string $message, int $statusCode = 400, array $errors = []): void
|
|
{
|
|
$response = [
|
|
'success' => false,
|
|
'message' => $message
|
|
];
|
|
|
|
if (!empty($errors)) {
|
|
$response['errors'] = $errors;
|
|
}
|
|
|
|
$this->jsonResponse($response, $statusCode);
|
|
}
|
|
|
|
/**
|
|
* Resposta de sucesso padronizada
|
|
*/
|
|
protected function successResponse(array $data = [], string $message = 'Success'): void
|
|
{
|
|
$response = [
|
|
'success' => true,
|
|
'message' => $message
|
|
];
|
|
|
|
if (!empty($data)) {
|
|
$response['data'] = $data;
|
|
}
|
|
|
|
$this->jsonResponse($response);
|
|
}
|
|
|
|
/**
|
|
* Validar se o utilizador está autenticado
|
|
*/
|
|
/**
|
|
* Detectar se é uma página pública baseado no contexto
|
|
*/
|
|
protected function isPublicPage(): bool
|
|
{
|
|
// Detectar por URL patterns
|
|
$currentUrl = $_SERVER['REQUEST_URI'] ?? '';
|
|
$publicPatterns = [
|
|
'/public/',
|
|
'/api/ecommerce/products',
|
|
'/api/ecommerce/filter-options',
|
|
'/api/error-monitoring/',
|
|
'/error-monitoring/'
|
|
];
|
|
|
|
foreach ($publicPatterns as $pattern) {
|
|
if (strpos($currentUrl, $pattern) !== false) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
// Detectar por layout/tema
|
|
$layout = $_GET['layout'] ?? $_POST['layout'] ?? '';
|
|
if ($layout === 'public' || $layout === 'public-blank') {
|
|
return true;
|
|
}
|
|
|
|
// Detectar por referer se for API
|
|
if (strpos($currentUrl, '/api/') !== false) {
|
|
$referer = $_SERVER['HTTP_REFERER'] ?? '';
|
|
if (strpos($referer, '/public/') !== false) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
protected function requireAuth(): void
|
|
{
|
|
// Se for página pública, não requer autenticação
|
|
if ($this->isPublicPage()) {
|
|
return;
|
|
}
|
|
|
|
if (!Auth::check()) {
|
|
$this->errorResponse('Authentication required', 401);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if request is authenticated via session OR API key
|
|
*/
|
|
protected function apiOrAuthRequired(): void
|
|
{
|
|
// Check session authentication first
|
|
if (Auth::check()) {
|
|
return;
|
|
}
|
|
|
|
// Check Bearer token
|
|
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
|
|
if (stripos($authHeader, 'Bearer ') === 0) {
|
|
$token = trim(substr($authHeader, 7));
|
|
$expectedKey = $_ENV['REDIRECTS_API_KEY'] ?? '';
|
|
|
|
if ($expectedKey && hash_equals($expectedKey, $token)) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Neither session nor API key is valid
|
|
$this->errorResponse('Unauthorized - Authentication required', 401);
|
|
}
|
|
|
|
/**
|
|
* Obter dados sanitizados do request
|
|
*/
|
|
protected function getSanitizedInput(): array
|
|
{
|
|
return InputSanitizer::all('POST');
|
|
}
|
|
|
|
/**
|
|
* Obter um parâmetro específico sanitizado
|
|
*/
|
|
protected function getSanitizedParam(string $key, $default = null)
|
|
{
|
|
$input = $this->getSanitizedInput();
|
|
return $input[$key] ?? $default;
|
|
}
|
|
|
|
/**
|
|
* Log de atividade
|
|
*/
|
|
protected function logActivity(string $action, array $context = []): void
|
|
{
|
|
ErrorReporter::report(new \Exception("Activity: $action"), $context);
|
|
}
|
|
|
|
// =============================================================================
|
|
// MÉTODOS DE VALIDAÇÃO AUTOMÁTICA
|
|
// =============================================================================
|
|
|
|
/**
|
|
* Validar dados com regras
|
|
*/
|
|
protected function validate(array $data, array $rules, array $messages = []): bool
|
|
{
|
|
$this->validator = Validator::make($data, $rules, $messages);
|
|
return $this->validator->validate();
|
|
}
|
|
|
|
/**
|
|
* Validar dados automaticamente usando ValidatorFactory
|
|
*/
|
|
protected function validateAuto(array $data, string $type): array
|
|
{
|
|
return ValidatorFactory::validate($data, $type);
|
|
}
|
|
|
|
/**
|
|
* Validar e sanitizar dados automaticamente
|
|
*/
|
|
protected function validateAndSanitizeAuto(array $data, string $type): array
|
|
{
|
|
return ValidatorFactory::validateAndSanitize($data, $type);
|
|
}
|
|
|
|
/**
|
|
* Validar POST automaticamente
|
|
*/
|
|
protected function validatePostAuto(string $type): array
|
|
{
|
|
$data = $this->getSanitizedInput();
|
|
return $this->validateAuto($data, $type);
|
|
}
|
|
|
|
/**
|
|
* Validar POST e retornar resposta de erro se falhar
|
|
*/
|
|
protected function validatePostAutoOrFail(string $type): array
|
|
{
|
|
$data = $this->getSanitizedInput();
|
|
$result = $this->validateAndSanitizeAuto($data, $type);
|
|
|
|
if (!$result['success']) {
|
|
$this->errorResponse(
|
|
$result['first_error'] ?? 'Validation failed',
|
|
422,
|
|
$result['errors']
|
|
);
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Validar dados sanitizados do POST
|
|
*/
|
|
protected function validatePost(array $rules, array $messages = []): bool
|
|
{
|
|
$data = $this->getSanitizedInput();
|
|
return $this->validate($data, $rules, $messages);
|
|
}
|
|
|
|
/**
|
|
* Validar dados sanitizados do GET
|
|
*/
|
|
protected function validateGet(array $rules, array $messages = []): bool
|
|
{
|
|
$data = InputSanitizer::all('GET');
|
|
return $this->validate($data, $rules, $messages);
|
|
}
|
|
|
|
/**
|
|
* Validar e retornar resposta de erro se falhar
|
|
*/
|
|
protected function validateOrFail(array $data, array $rules, array $messages = []): bool
|
|
{
|
|
if (!$this->validate($data, $rules, $messages)) {
|
|
$this->validationErrorResponse();
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Validar POST e retornar resposta de erro se falhar
|
|
*/
|
|
protected function validatePostOrFail(array $rules, array $messages = []): bool
|
|
{
|
|
if (!$this->validatePost($rules, $messages)) {
|
|
$this->validationErrorResponse();
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Validar GET e retornar resposta de erro se falhar
|
|
*/
|
|
protected function validateGetOrFail(array $rules, array $messages = []): bool
|
|
{
|
|
if (!$this->validateGet($rules, $messages)) {
|
|
$this->validationErrorResponse();
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Resposta de erro de validação
|
|
*/
|
|
protected function validationErrorResponse(): void
|
|
{
|
|
if ($this->validator) {
|
|
$errors = $this->validator->getErrors();
|
|
$firstError = $this->validator->getFirstError();
|
|
|
|
$this->errorResponse(
|
|
$firstError ?? 'Validation failed',
|
|
422,
|
|
$errors
|
|
);
|
|
} else {
|
|
$this->errorResponse('Validation failed', 422);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter erros de validação
|
|
*/
|
|
protected function getValidationErrors(): array
|
|
{
|
|
return $this->validator ? $this->validator->getErrors() : [];
|
|
}
|
|
|
|
/**
|
|
* Obter primeiro erro de validação
|
|
*/
|
|
protected function getFirstValidationError(): ?string
|
|
{
|
|
return $this->validator ? $this->validator->getFirstError() : null;
|
|
}
|
|
|
|
/**
|
|
* Verificar se campo tem erro de validação
|
|
*/
|
|
protected function hasValidationError(string $field): bool
|
|
{
|
|
return $this->validator ? $this->validator->hasError($field) : false;
|
|
}
|
|
|
|
/**
|
|
* Obter erros de um campo específico
|
|
*/
|
|
protected function getFieldValidationErrors(string $field): array
|
|
{
|
|
return $this->validator ? $this->validator->getFieldErrors($field) : [];
|
|
}
|
|
|
|
// =============================================================================
|
|
// REGRAS DE VALIDAÇÃO PRÉ-DEFINIDAS
|
|
// =============================================================================
|
|
|
|
/**
|
|
* Regras para criação de utilizador
|
|
*/
|
|
protected function getUserCreateRules(): array
|
|
{
|
|
return [
|
|
'first_name' => 'required|min:2|max:50|alpha',
|
|
'last_name' => 'required|min:2|max:50|alpha',
|
|
'email' => 'required|email|max:100',
|
|
'username' => 'required|min:3|max:20|alphanumeric',
|
|
'password' => 'required|min:8|strong_password',
|
|
'password_confirmation' => 'required|confirmed',
|
|
'role' => 'required|in:admin,user,manager'
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Regras para atualização de utilizador
|
|
*/
|
|
protected function getUserUpdateRules(): array
|
|
{
|
|
return [
|
|
'first_name' => 'required|min:2|max:50|alpha',
|
|
'last_name' => 'required|min:2|max:50|alpha',
|
|
'email' => 'required|email|max:100',
|
|
'phone' => 'nullable|phone|max:20',
|
|
'city' => 'nullable|max:100',
|
|
'country' => 'nullable|max:100',
|
|
'website' => 'nullable|url|max:255',
|
|
'job_title' => 'nullable|max:100',
|
|
'company_name' => 'nullable|max:100',
|
|
'description' => 'nullable|max:500'
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Regras para criação de contacto
|
|
*/
|
|
protected function getContactCreateRules(): array
|
|
{
|
|
return [
|
|
'first_name' => 'required|min:2|max:50|alpha',
|
|
'last_name' => 'required|min:2|max:50|alpha',
|
|
'email' => 'required|email|max:100',
|
|
'phone' => 'nullable|phone|max:20',
|
|
'mobile' => 'nullable|phone|max:20',
|
|
'job_title' => 'nullable|max:100',
|
|
'company_id' => 'nullable|integer',
|
|
'website' => 'nullable|url|max:255',
|
|
'address' => 'nullable|max:255',
|
|
'city' => 'nullable|max:100',
|
|
'state' => 'nullable|max:100',
|
|
'country' => 'nullable|max:100',
|
|
'zip_code' => 'nullable|max:20',
|
|
'notes' => 'nullable|max:1000',
|
|
'status' => 'required|in:active,inactive,lead,customer,prospect',
|
|
'source' => 'nullable|max:100'
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Regras para criação de empresa
|
|
*/
|
|
protected function getCompanyCreateRules(): array
|
|
{
|
|
return [
|
|
'name' => 'required|min:2|max:255',
|
|
'email' => 'nullable|email|max:100',
|
|
'phone' => 'nullable|phone|max:20',
|
|
'website' => 'nullable|url|max:255',
|
|
'address' => 'nullable|max:255',
|
|
'city' => 'nullable|max:100',
|
|
'state' => 'nullable|max:100',
|
|
'country' => 'nullable|max:100',
|
|
'zip_code' => 'nullable|max:20',
|
|
'industry' => 'nullable|max:100',
|
|
'company_size' => 'nullable|in:1-10,11-50,51-200,201-500,501-1000,1000+',
|
|
'annual_revenue' => 'nullable|decimal',
|
|
'description' => 'nullable|max:1000',
|
|
'notes' => 'nullable|max:1000',
|
|
'status' => 'required|in:active,inactive,prospect,customer,partner',
|
|
'source' => 'nullable|max:100'
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Regras para criação de negócio
|
|
*/
|
|
protected function getDealCreateRules(): array
|
|
{
|
|
return [
|
|
'title' => 'required|min:3|max:255',
|
|
'description' => 'nullable|max:1000',
|
|
'value' => 'nullable|decimal|min_value:0',
|
|
'stage' => 'required|in:new,qualification,proposal,negotiation,closed_won,closed_lost',
|
|
'status' => 'required|in:open,closed',
|
|
'company_id' => 'nullable|integer',
|
|
'contact_id' => 'nullable|integer',
|
|
'expected_close_date' => 'nullable|date',
|
|
'probability' => 'nullable|integer|between:0,100',
|
|
'source' => 'nullable|max:100',
|
|
'notes' => 'nullable|max:1000'
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Regras para criação de lead
|
|
*/
|
|
protected function getLeadCreateRules(): array
|
|
{
|
|
return [
|
|
'name' => 'required|min:2|max:255',
|
|
'email' => 'required|email|max:100',
|
|
'phone' => 'nullable|phone|max:20',
|
|
'company' => 'nullable|max:255',
|
|
'job_title' => 'nullable|max:100',
|
|
'source' => 'nullable|max:100',
|
|
'status' => 'required|in:new,contacted,qualified,converted,lost',
|
|
'score' => 'nullable|integer|between:1,10',
|
|
'notes' => 'nullable|max:1000',
|
|
'assigned_to' => 'nullable|integer'
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Regras para criação de tarefa
|
|
*/
|
|
protected function getTaskCreateRules(): array
|
|
{
|
|
return [
|
|
'title' => 'required|min:3|max:255',
|
|
'description' => 'nullable|max:1000',
|
|
'due_date' => 'required|date',
|
|
'priority' => 'required|in:low,medium,high,urgent',
|
|
'status' => 'required|in:pending,in_progress,completed,cancelled',
|
|
'assigned_to' => 'nullable|integer',
|
|
'related_type' => 'nullable|in:contact,company,deal,lead',
|
|
'related_id' => 'nullable|integer',
|
|
'notes' => 'nullable|max:1000'
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Regras para criação de campanha
|
|
*/
|
|
protected function getCampaignCreateRules(): array
|
|
{
|
|
return [
|
|
'name' => 'required|min:3|max:255',
|
|
'description' => 'nullable|max:1000',
|
|
'status' => 'required|in:active,inactive,draft,paused',
|
|
'budget' => 'nullable|decimal|min_value:0',
|
|
'start_date' => 'required|date',
|
|
'end_date' => 'nullable|date',
|
|
'target_audience' => 'nullable|max:500',
|
|
'objectives' => 'nullable|max:500',
|
|
'tracking_code' => 'nullable|max:100',
|
|
'notes' => 'nullable|max:1000'
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Regras para upload de arquivo
|
|
*/
|
|
protected function getFileUploadRules(): array
|
|
{
|
|
return [
|
|
'file' => 'required|file|size:5120', // 5MB max
|
|
'allowed_types' => 'nullable|in:image,document,video,audio'
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Regras para upload de imagem
|
|
*/
|
|
protected function getImageUploadRules(): array
|
|
{
|
|
return [
|
|
'image' => 'required|image|size:2048', // 2MB max
|
|
'max_width' => 'nullable|integer|min_value:1|max_value:5000',
|
|
'max_height' => 'nullable|integer|min_value:1|max_value:5000'
|
|
];
|
|
}
|
|
|
|
// =============================================================================
|
|
// MÉTODOS UTILITÁRIOS ADICIONAIS
|
|
// =============================================================================
|
|
|
|
/**
|
|
* Redirecionar com mensagem de sucesso
|
|
*/
|
|
protected function redirectWithSuccess(string $url, string $message): void
|
|
{
|
|
$separator = strpos($url, '?') !== false ? '&' : '?';
|
|
header("Location: {$url}{$separator}success=" . urlencode($message));
|
|
exit();
|
|
}
|
|
|
|
/**
|
|
* Redirecionar com mensagem de erro
|
|
*/
|
|
protected function redirectWithError(string $url, string $message): void
|
|
{
|
|
$separator = strpos($url, '?') !== false ? '&' : '?';
|
|
header("Location: {$url}{$separator}error=" . urlencode($message));
|
|
exit();
|
|
}
|
|
|
|
/**
|
|
* Verificar se é requisição AJAX
|
|
*/
|
|
protected function isAjaxRequest(): bool
|
|
{
|
|
return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
|
|
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
|
|
}
|
|
|
|
/**
|
|
* Verificar se é requisição POST
|
|
*/
|
|
protected function isPostRequest(): bool
|
|
{
|
|
return $_SERVER['REQUEST_METHOD'] === 'POST';
|
|
}
|
|
|
|
/**
|
|
* Verificar se é requisição GET
|
|
*/
|
|
protected function isGetRequest(): bool
|
|
{
|
|
return $_SERVER['REQUEST_METHOD'] === 'GET';
|
|
}
|
|
|
|
/**
|
|
* Obter IP do cliente
|
|
*/
|
|
protected function getClientIp(): string
|
|
{
|
|
$ipKeys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
|
|
|
|
foreach ($ipKeys as $key) {
|
|
if (!empty($_SERVER[$key])) {
|
|
$ip = $_SERVER[$key];
|
|
if (strpos($ip, ',') !== false) {
|
|
$ip = trim(explode(',', $ip)[0]);
|
|
}
|
|
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
|
|
return $ip;
|
|
}
|
|
}
|
|
}
|
|
|
|
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
|
|
}
|
|
|
|
/**
|
|
* Obter User Agent
|
|
*/
|
|
protected function getUserAgent(): string
|
|
{
|
|
return $_SERVER['HTTP_USER_AGENT'] ?? '';
|
|
}
|
|
|
|
/**
|
|
* Log de acesso
|
|
*/
|
|
protected function logAccess(string $action, array $context = []): void
|
|
{
|
|
$context['ip'] = $this->getClientIp();
|
|
$context['user_agent'] = $this->getUserAgent();
|
|
$context['user_id'] = Auth::id();
|
|
$context['action'] = $action;
|
|
|
|
ErrorReporter::info("Access: $action", $context);
|
|
}
|
|
}
|