Files
1sonhador c1ddf3548d fix: Corrigir comentários em Português - remover gerúndio incorreto
- Substituir "usando" por "com" ou "através de" onde apropriado
- Corrigir "adicionar à fila para depois" para "adicionar à fila para processamento posterior"
- Melhorar clareza e correção gramatical nos comentários
2025-10-30 10:03:01 +00:00

1316 lines
48 KiB
PHP

<?php
namespace App\Modules\Users\Controllers;
use App\Core\BaseController;
use App\Core\InputSanitizer;
use App\Core\View;
use App\Core\Auth;
use App\Core\ErrorReporter;
use App\Core\Sanitize;
use App\Modules\Users\Models\UserModel;
class UserController extends BaseController
{
private UserModel $userModel;
public function __construct()
{
parent::__construct('Users');
$this->userModel = new UserModel();
}
public function showProfile(): void
{
try {
// Autenticação obrigatória
$this->requireAuth();
// Obter ID do utilizador autenticado
$userId = Auth::id();
if (!$userId) {
throw new \Exception('User ID not found');
}
$userData = $this->userModel->find($userId);
if (!$userData) {
http_response_code(404);
echo 'Utilizador não encontrado';
return;
}
// Sanitizar dados do utilizador
$user = [
'first_name' => Sanitize::string($userData['first_name'] ?? 'N/A'),
'last_name' => Sanitize::string($userData['last_name'] ?? ''),
'username' => Sanitize::string($userData['username'] ?? 'N/A'),
'job_title' => Sanitize::string($userData['job_title'] ?? 'N/A'),
'company_name' => Sanitize::string($userData['company_name'] ?? 'N/A'),
'city' => Sanitize::string($userData['city'] ?? 'N/A'),
'country' => Sanitize::string($userData['country'] ?? 'N/A'),
'avatar' => \App\Core\View::asset('images/users/avatar-1.jpg'),
'profile_bg' => \App\Core\View::asset('images/profile-bg.jpg'),
'followers_count' => $this->getFollowersCount($userId),
'following_count' => $this->getFollowingCount($userId),
'email' => Sanitize::email($userData['email'] ?? 'N/A'),
'website' => Sanitize::url($userData['website'] ?? '#'),
'phone' => Sanitize::string($userData['phone'] ?? 'N/A'),
'zipcode' => Sanitize::string($userData['zipcode'] ?? 'N/A'),
'description' => Sanitize::string($userData['description'] ?? 'N/A'),
'joining_date' => Sanitize::string($userData['joining_date'] ?? 'N/A')
];
// Parse e sanitizar campos JSON
$skills = [];
$experience = [];
$education = [];
$socialLinks = [];
if (!empty($userData['skills'])) {
$skills = json_decode($userData['skills'], true) ?: [];
$skills = array_map('Sanitize::string', $skills);
}
if (!empty($userData['experience'])) {
$experience = json_decode($userData['experience'], true) ?: [];
// Sanitizar arrays de experiência
$experience = array_map(function($exp) {
return [
'title' => Sanitize::string($exp['title'] ?? ''),
'company' => Sanitize::string($exp['company'] ?? ''),
'description' => Sanitize::string($exp['description'] ?? ''),
'period' => Sanitize::string($exp['period'] ?? '')
];
}, $experience);
}
if (!empty($userData['education'])) {
$education = json_decode($userData['education'], true) ?: [];
// Sanitizar arrays de educação
$education = array_map(function($edu) {
return [
'degree' => Sanitize::string($edu['degree'] ?? ''),
'institution' => Sanitize::string($edu['institution'] ?? ''),
'year' => Sanitize::string($edu['year'] ?? '')
];
}, $education);
}
if (!empty($userData['social_links'])) {
$socialLinks = json_decode($userData['social_links'], true) ?: [];
// Sanitizar links sociais
$socialLinks = array_map('Sanitize::url', $socialLinks);
}
$userProfile = [
'bio' => Sanitize::string($userData['bio'] ?? 'No bio available.'),
'location' => Sanitize::string($userData['location'] ?? 'N/A'),
'skills' => $skills,
'experience' => $experience,
'education' => $education,
'social_links' => $socialLinks,
'profile_completion' => $this->calculateProfileCompletion($userData)
];
// Render the main layout with the profile page content
View::render('layouts/main.php', [
'title' => 'User Profile',
'page_content' => function() use ($user, $userProfile) {
View::render('layouts/page-title.php', ['pagetitle' => 'Users', 'title' => 'Profile']);
View::render('@pages/profile', [
'user' => $user,
'profile' => $userProfile
]);
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'users_show_profile', 'userId' => $userId ?? 0]);
if (strpos($e->getMessage(), 'Authentication required') !== false) {
header('Location: /auth/login');
exit;
} else {
http_response_code(500);
echo 'Erro interno do servidor';
}
}
}
/**
* Show the profile edit form.
*/
public function showEditProfile(): void
{
try {
// Autenticação obrigatória
$this->requireAuth();
$userId = Auth::id();
if (!$userId) {
throw new \Exception('User ID not found');
}
$userData = $this->userModel->find($userId);
if (!$userData) {
http_response_code(404);
echo 'Utilizador não encontrado';
return;
}
// Parse e sanitizar campos JSON
$skills = [];
$experience = [];
$education = [];
$socialLinks = [];
if (!empty($userData['skills'])) {
$skills = json_decode($userData['skills'], true) ?: [];
$skills = array_map('Sanitize::string', $skills);
}
if (!empty($userData['experience'])) {
$experience = json_decode($userData['experience'], true) ?: [];
$experience = array_map(function($exp) {
return [
'title' => Sanitize::string($exp['title'] ?? ''),
'company' => Sanitize::string($exp['company'] ?? ''),
'description' => Sanitize::string($exp['description'] ?? ''),
'period' => Sanitize::string($exp['period'] ?? '')
];
}, $experience);
}
if (!empty($userData['education'])) {
$education = json_decode($userData['education'], true) ?: [];
$education = array_map(function($edu) {
return [
'degree' => Sanitize::string($edu['degree'] ?? ''),
'institution' => Sanitize::string($edu['institution'] ?? ''),
'year' => Sanitize::string($edu['year'] ?? '')
];
}, $education);
}
if (!empty($userData['social_links'])) {
$socialLinks = json_decode($userData['social_links'], true) ?: [];
$socialLinks = array_map('Sanitize::url', $socialLinks);
}
$user = [
'first_name' => Sanitize::string($userData['first_name'] ?? ''),
'last_name' => Sanitize::string($userData['last_name'] ?? ''),
'email' => Sanitize::email($userData['email'] ?? ''),
'phone' => Sanitize::string($userData['phone'] ?? ''),
'city' => Sanitize::string($userData['city'] ?? ''),
'country' => Sanitize::string($userData['country'] ?? ''),
'zipcode' => Sanitize::string($userData['zipcode'] ?? ''),
'website' => Sanitize::url($userData['website'] ?? ''),
'job_title' => Sanitize::string($userData['job_title'] ?? ''),
'company_name' => Sanitize::string($userData['company_name'] ?? ''),
'description' => Sanitize::string($userData['description'] ?? ''),
'avatar' => Sanitize::string($userData['avatar'] ?? '/assets/images/users/avatar-1.jpg')
];
$profile = [
'bio' => Sanitize::string($userData['bio'] ?? ''),
'location' => Sanitize::string($userData['location'] ?? ''),
'skills' => $skills,
'experience' => $experience,
'education' => $education,
'social_links' => $socialLinks
];
View::render('layouts/main.php', [
'title' => 'Edit Profile',
'page_content' => function() use ($user, $profile) {
View::render('layouts/page-title.php', ['pagetitle' => 'Users', 'title' => 'Edit Profile']);
View::render('@pages/profile-edit', [
'user' => $user,
'profile' => $profile
]);
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'users_show_edit_profile', 'userId' => $userId ?? 0]);
if (strpos($e->getMessage(), 'Authentication required') !== false) {
header('Location: /auth/login');
exit;
} else {
http_response_code(500);
echo 'Erro interno do servidor';
}
}
}
/**
* Handle profile update form submission.
*/
public function updateProfile(): void
{
try {
// Autenticação obrigatória
$this->requireAuth();
$userId = Auth::id();
if (!$userId) {
throw new \Exception('User ID not found');
}
// ✅ NOVO: Validação automática com ValidatorFactory
$validation = $this->validatePostAutoOrFail('user.update');
// Se chegou aqui, a validação passou - dados já sanitizados
$userData = $validation['data'];
// Sanitizar e validar dados do perfil
$skills = array_filter(explode(',', InputSanitizer::get('skills', 'POST') ?? ''), 'trim');
$skills = array_map('Sanitize::string', $skills);
$profileData = [
'bio' => Sanitize::string(InputSanitizer::get('bio', 'POST') ?? ''),
'location' => Sanitize::string(InputSanitizer::get('location', 'POST') ?? ''),
'skills' => json_encode($skills),
'social_links' => json_encode([
'linkedin' => Sanitize::url(InputSanitizer::get('linkedin', 'POST') ?? ''),
'github' => Sanitize::url(InputSanitizer::get('github', 'POST') ?? ''),
'twitter' => Sanitize::url(InputSanitizer::get('twitter', 'POST') ?? '')
])
];
// Update user and profile
$success = $this->userModel->update($userId, $userData, $profileData);
if ($success) {
$this->successResponse([], 'Profile updated successfully');
} else {
$this->errorResponse('Failed to update profile');
}
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'users_update_profile', 'userId' => $userId ?? 0]);
$this->errorResponse('Internal server error', 500);
}
}
/**
* Admin users management page.
*/
public function adminUsers(): void
{
try {
// Autenticação obrigatória
$this->requireAuth();
// Verificar se é admin
if (!Auth::isAdmin()) {
http_response_code(403);
echo 'Acesso negado';
return;
}
View::render('layouts/main.php', [
'title' => 'Gestão de Utilizadores',
'page_content' => function() {
View::render('layouts/page-title.php', [
'pagetitle' => 'Gestão',
'title' => 'Utilizadores'
]);
View::render('@users/admin-users');
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'users_admin_users']);
if (strpos($e->getMessage(), 'Authentication required') !== false) {
header('Location: /auth/login');
exit;
} else {
http_response_code(500);
echo 'Erro interno do servidor';
}
}
}
/**
* Admin roles management page.
*/
public function adminRoles(): void
{
try {
// Autenticação obrigatória
$this->requireAuth();
// Verificar se é admin
if (!Auth::isAdmin()) {
http_response_code(403);
echo 'Acesso negado';
return;
}
View::render('layouts/main.php', [
'title' => 'Gestão de Perfis',
'page_content' => function() {
View::render('layouts/page-title.php', [
'pagetitle' => 'Gestão',
'title' => 'Perfis'
]);
View::render('@users/admin-roles.php');
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'users_admin_roles']);
if (strpos($e->getMessage(), 'Authentication required') !== false) {
header('Location: /auth/login');
exit;
} else {
http_response_code(500);
echo 'Erro interno do servidor';
}
}
}
// API Methods for Admin Users Management
/**
* API: Get all users with pagination and search
*/
public function apiGetUsers(): void
{
try {
// Middleware já faz autenticação (apiOrAuth)
// Verificar se é admin
if (!Auth::isAdmin()) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Acesso negado']);
exit;
}
$search = Sanitize::string($_GET['search'] ?? '');
$sort = Sanitize::string($_GET['sort'] ?? 'name');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = max(1, min(100, (int)($_GET['per_page'] ?? 10)));
$showDeleted = filter_var($_GET['show_deleted'] ?? false, FILTER_VALIDATE_BOOLEAN);
// Debug log
error_log("API Users - show_deleted: " . ($showDeleted ? 'true' : 'false'));
$users = $this->userModel->getAllForAdmin($search, $sort, $page, $perPage, $showDeleted);
$totalUsers = $this->userModel->getTotalForAdmin($search, $showDeleted);
$totalPages = ceil($totalUsers / $perPage);
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'users' => $users,
'current_page' => $page,
'per_page' => $perPage,
'total_pages' => $totalPages,
'total' => $totalUsers
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_get_users']);
http_response_code(500);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro interno do servidor']);
}
exit;
}
/**
* API: Reset user password
*/
public function apiResetPassword(int $id): void
{
try {
// Middleware já faz autenticação (apiOrAuth)
if (!Auth::isAdmin()) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Acesso negado']);
exit;
}
// Don't allow resetting your own password
if ($id === Auth::id()) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Não pode fazer reset da sua própria password']);
exit;
}
// Generate new random password
$newPassword = bin2hex(random_bytes(8)); // 16 character password
$hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
$success = $this->userModel->updatePassword($id, $hashedPassword);
if ($success) {
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'message' => 'Password reset com sucesso',
'new_password' => $newPassword
]);
} else {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro ao reset password']);
}
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_reset_password', 'userId' => $id]);
http_response_code(500);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro interno do servidor']);
}
exit;
}
/**
* API: Get single user by ID
*/
public function apiGetUser(int $id): void
{
try {
// Middleware já faz autenticação (apiOrAuth)
if (!Auth::isAdmin()) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Acesso negado']);
exit;
}
$user = $this->userModel->findForAdmin($id);
if (!$user) {
http_response_code(404);
header('Content-Type: application/json');
echo json_encode(['error' => 'Utilizador não encontrado']);
exit;
}
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'user' => $user
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_get_user', 'userId' => $id]);
http_response_code(500);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro interno do servidor']);
}
exit;
}
/**
* API: Create new user
*/
public function apiCreateUser(): void
{
try {
// Middleware já faz autenticação (apiOrAuth)
if (!Auth::isAdmin()) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Acesso negado']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
$userData = [
'first_name' => Sanitize::string($input['first_name'] ?? ''),
'last_name' => Sanitize::string($input['last_name'] ?? ''),
'email' => Sanitize::email($input['email'] ?? ''),
'password' => $input['password'] ?? '',
'role' => Sanitize::string($input['role'] ?? 'user'),
'is_active' => (int)($input['is_active'] ?? 1)
];
// Basic validation
if (empty($userData['first_name']) || empty($userData['email']) || empty($userData['password'])) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Campos obrigatórios em falta']);
exit;
}
if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Email inválido']);
exit;
}
$userId = $this->userModel->createForAdmin($userData);
if ($userId) {
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'message' => 'Utilizador criado com sucesso',
'user_id' => $userId
]);
} else {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro ao criar utilizador']);
}
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_create_user']);
http_response_code(500);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro interno do servidor']);
}
exit;
}
/**
* API: Update user
*/
public function apiUpdateUser(int $id): void
{
try {
// Middleware já faz autenticação (apiOrAuth)
if (!Auth::isAdmin()) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Acesso negado']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
$userData = [
'first_name' => Sanitize::string($input['first_name'] ?? ''),
'last_name' => Sanitize::string($input['last_name'] ?? ''),
'email' => Sanitize::email($input['email'] ?? ''),
'role' => Sanitize::string($input['role'] ?? 'user'),
'is_active' => (int)($input['is_active'] ?? 1)
];
// Only include password if provided
if (!empty($input['password'])) {
$userData['password'] = $input['password'];
}
// Basic validation
if (empty($userData['first_name']) || empty($userData['email'])) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Campos obrigatórios em falta']);
exit;
}
if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Email inválido']);
exit;
}
$success = $this->userModel->updateForAdmin($id, $userData);
if ($success) {
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'message' => 'Utilizador atualizado com sucesso'
]);
} else {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro ao atualizar utilizador']);
}
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_update_user', 'userId' => $id]);
http_response_code(500);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro interno do servidor']);
}
exit;
}
/**
* API: Delete user
*/
public function apiDeleteUser(int $id): void
{
try {
// Middleware já faz autenticação (apiOrAuth)
if (!Auth::isAdmin()) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Acesso negado']);
exit;
}
// Don't allow deleting yourself
if ($id === Auth::id()) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Não pode eliminar a sua própria conta']);
exit;
}
$success = $this->userModel->deleteForAdmin($id);
if ($success) {
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'message' => 'Utilizador eliminado com sucesso'
]);
} else {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro ao eliminar utilizador']);
}
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_delete_user', 'userId' => $id]);
http_response_code(500);
header('Content-Type: application/json');
echo json_encode(['error' => 'Erro interno do servidor']);
}
exit;
}
/**
* Get followers count for a user
*/
private function getFollowersCount(int $userId): int
{
// For now, return 0 as we don't have a followers system implemented
// This can be implemented when the social features are added
return 0;
}
/**
* Get following count for a user
*/
private function getFollowingCount(int $userId): int
{
// For now, return 0 as we don't have a following system implemented
// This can be implemented when the social features are added
return 0;
}
/**
* Calculate profile completion percentage
*/
private function calculateProfileCompletion(array $userData): int
{
$totalFields = 10;
$completedFields = 0;
// Check required fields
if (!empty($userData['first_name'])) $completedFields++;
if (!empty($userData['last_name'])) $completedFields++;
if (!empty($userData['email'])) $completedFields++;
if (!empty($userData['bio'])) $completedFields++;
if (!empty($userData['job_title'])) $completedFields++;
if (!empty($userData['city'])) $completedFields++;
if (!empty($userData['country'])) $completedFields++;
if (!empty($userData['phone'])) $completedFields++;
if (!empty($userData['skills'])) $completedFields++;
if (!empty($userData['avatar'])) $completedFields++;
return (int) round(($completedFields / $totalFields) * 100);
}
// --- INDIVIDUAL USER MANAGEMENT METHODS (Missing functionality) ---
/**
* Show specific user details (admin function)
*/
public function showUser(int $id): void
{
try {
$this->requireAuth();
$userData = $this->userModel->find($id);
if (!$userData) {
http_response_code(404);
echo 'Utilizador não encontrado';
return;
}
$user = [
'id' => $id,
'first_name' => Sanitize::string($userData['first_name'] ?? ''),
'last_name' => Sanitize::string($userData['last_name'] ?? ''),
'username' => Sanitize::string($userData['username'] ?? ''),
'email' => Sanitize::email($userData['email'] ?? ''),
'status' => Sanitize::string($userData['status'] ?? 'active')
];
View::render('layouts/main.php', [
'title' => 'Utilizador: ' . $user['first_name'] . ' ' . $user['last_name'],
'page_name' => 'user-view',
'page_content' => function() use ($user) {
View::render('@users/user-view.php', ['user' => $user]);
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'show_user', 'user_id' => $id]);
http_response_code(500);
echo 'Erro interno';
}
}
/**
* Show specific user profile (admin function)
*/
public function showUserProfile(int $id): void
{
try {
$this->requireAuth();
$userData = $this->userModel->find($id);
if (!$userData) {
http_response_code(404);
echo 'Utilizador não encontrado';
return;
}
$user = [
'id' => $id,
'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'] ?? '')
];
View::render('layouts/main.php', [
'title' => 'Perfil: ' . $user['first_name'] . ' ' . $user['last_name'],
'page_name' => 'user-profile',
'page_content' => function() use ($user) {
View::render('@users/user-profile.php', compact('user'));
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'show_user_profile', 'user_id' => $id]);
http_response_code(500);
echo 'Erro interno';
}
}
/**
* Show edit user form (admin function)
*/
public function showEditUser(int $id): void
{
try {
$this->requireAuth();
$userData = $this->userModel->find($id);
if (!$userData) {
http_response_code(404);
echo 'Utilizador não encontrado';
return;
}
$user = [
'id' => $id,
'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'] ?? ''),
'status' => Sanitize::string($userData['status'] ?? 'active')
];
View::render('layouts/main.php', [
'title' => 'Editar: ' . $user['first_name'] . ' ' . $user['last_name'],
'page_name' => 'user-edit',
'page_content' => function() use ($user) {
View::render('@users/user-edit.php', compact('user'));
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'show_edit_user', 'user_id' => $id]);
http_response_code(500);
echo 'Erro interno';
}
}
/**
* Show user settings (admin function)
*/
public function showUserSettings(int $id): void
{
try {
$this->requireAuth();
$userData = $this->userModel->find($id);
if (!$userData) {
http_response_code(404);
echo 'Utilizador não encontrado';
return;
}
$user = [
'id' => $id,
'first_name' => Sanitize::string($userData['first_name'] ?? ''),
'last_name' => Sanitize::string($userData['last_name'] ?? ''),
'username' => Sanitize::string($userData['username'] ?? ''),
'email' => Sanitize::email($userData['email'] ?? ''),
'status' => Sanitize::string($userData['status'] ?? 'active'),
'preferences' => json_decode($userData['preferences'] ?? '{}', true)
];
View::render('layouts/main.php', [
'title' => 'Definições: ' . $user['first_name'] . ' ' . $user['last_name'],
'page_name' => 'user-settings',
'page_content' => function() use ($user) {
View::render('@users/user-settings.php', compact('user'));
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'show_user_settings', 'user_id' => $id]);
http_response_code(500);
echo 'Erro interno';
}
}
/**
* Show user permissions (admin function)
*/
public function showUserPermissions(int $id): void
{
try {
$this->requireAuth();
$userData = $this->userModel->find($id);
if (!$userData) {
http_response_code(404);
echo 'Utilizador não encontrado';
return;
}
$user = [
'id' => $id,
'first_name' => Sanitize::string($userData['first_name'] ?? ''),
'last_name' => Sanitize::string($userData['last_name'] ?? ''),
'username' => Sanitize::string($userData['username'] ?? ''),
'email' => Sanitize::email($userData['email'] ?? ''),
'role' => Sanitize::string($userData['role'] ?? 'user'),
'permissions' => json_decode($userData['permissions'] ?? '[]', true)
];
View::render('layouts/main.php', [
'title' => 'Permissões: ' . $user['first_name'] . ' ' . $user['last_name'],
'page_name' => 'user-permissions',
'page_content' => function() use ($user) {
View::render('@users/user-permissions.php', compact('user'));
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'show_user_permissions', 'user_id' => $id]);
http_response_code(500);
echo 'Erro interno';
}
}
/**
* Update specific user (admin function)
*/
public function updateUser(int $id): void
{
try {
$this->requireAuth();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo 'Método não permitido';
return;
}
$userData = $this->userModel->find($id);
if (!$userData) {
http_response_code(404);
echo 'Utilizador não encontrado';
return;
}
// Update user with sanitized data
$updateData = [
'first_name' => Sanitize::string($_POST['first_name'] ?? ''),
'last_name' => Sanitize::string($_POST['last_name'] ?? ''),
'email' => Sanitize::email($_POST['email'] ?? ''),
'job_title' => Sanitize::string($_POST['job_title'] ?? ''),
'company_name' => Sanitize::string($_POST['company_name'] ?? ''),
'status' => Sanitize::string($_POST['status'] ?? 'active')
];
$success = $this->userModel->update($id, $updateData);
if ($success) {
header('Location: /users/' . $id . '?updated=1', true, 302);
} else {
http_response_code(500);
echo 'Erro ao actualizar utilizador';
}
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'update_user', 'user_id' => $id]);
http_response_code(500);
echo 'Erro interno';
}
}
/**
* View individual role
*/
public function viewRole(int $id): void
{
try {
$this->requireAuth();
if (!Auth::isAdmin()) {
http_response_code(403);
echo 'Acesso negado';
return;
}
$roleModel = new \App\Modules\Users\Models\RoleModel();
$role = $roleModel->getRoleWithUsers($id);
if (!$role) {
http_response_code(404);
echo 'Perfil não encontrado';
return;
}
View::render('layouts/main.php', [
'title' => 'Ver Perfil - ' . $role['name'],
'page_content' => function() use ($role) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Gestão',
'title' => 'Ver Perfil: ' . $role['name']
]);
View::render('@users/role-view.php', ['role' => $role]);
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'view_role', 'role_id' => $id]);
http_response_code(500);
echo 'Erro interno do servidor';
}
}
/**
* Edit individual role
*/
public function editRole(int $id): void
{
try {
$this->requireAuth();
if (!Auth::isAdmin()) {
http_response_code(403);
echo 'Acesso negado';
return;
}
$roleModel = new \App\Modules\Users\Models\RoleModel();
$role = $roleModel->find($id);
if (!$role) {
http_response_code(404);
echo 'Perfil não encontrado';
return;
}
// Parse permissions if JSON
if (!empty($role['permissions'])) {
$role['permissions'] = json_decode($role['permissions'], true) ?: [];
} else {
$role['permissions'] = [];
}
View::render('layouts/main.php', [
'title' => 'Editar Perfil - ' . $role['name'],
'page_content' => function() use ($role) {
View::render('layouts/page-title.php', [
'pagetitle' => 'Gestão',
'title' => 'Editar Perfil: ' . $role['name']
]);
View::render('@users/role-edit.php', ['role' => $role]);
}
]);
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'edit_role', 'role_id' => $id]);
http_response_code(500);
echo 'Erro interno do servidor';
}
}
// ==========================================
// ROLES API METHODS
// ==========================================
/**
* API: Get all roles
*/
public function apiGetRoles(): void
{
try {
$this->apiOrAuthRequired();
// If authenticated via session, check if admin
if (Auth::check() && !Auth::isAdmin()) {
$this->errorResponse('Acesso negado - requer permissões de administrador', 403);
return;
}
// If using Bearer token, allow access (API key has full access)
$roleModel = new \App\Modules\Users\Models\RoleModel();
$roles = $roleModel->getAllWithUserCount();
// Format roles for frontend
$formattedRoles = array_map(function($role) {
// Parse permissions
$permissions = [];
if (!empty($role['permissions'])) {
$permissions = json_decode($role['permissions'], true) ?: [];
}
return [
'id' => (int)$role['id'],
'name' => $role['name'],
'description' => $role['description'] ?? '',
'permissions' => $permissions,
'users_count' => (int)($role['users_count'] ?? 0),
'users' => [], // Empty for listing, will be loaded on detail view
'status' => $role['is_active'] ? 'active' : 'inactive',
'type' => $this->getRoleType($role['name']),
'created_at' => $role['created_at'] ?? null,
'updated_at' => $role['updated_at'] ?? null
];
}, $roles);
$this->successResponse([
'roles' => $formattedRoles
], 'Roles retrieved successfully');
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_get_roles']);
$this->errorResponse('Erro ao carregar perfis', 500);
}
}
/**
* API: Get single role
*/
public function apiGetRole(int $id): void
{
try {
$this->apiOrAuthRequired();
// If authenticated via session, check if admin
if (Auth::check() && !Auth::isAdmin()) {
$this->errorResponse('Acesso negado', 403);
return;
}
// If using Bearer token, allow access (API key has full access)
$roleModel = new \App\Modules\Users\Models\RoleModel();
$role = $roleModel->getRoleWithUsers($id);
if (!$role) {
$this->errorResponse('Perfil não encontrado', 404);
return;
}
$this->successResponse([
'role' => $role
], 'Role retrieved successfully');
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_get_role', 'role_id' => $id]);
$this->errorResponse('Erro ao carregar perfil', 500);
}
}
/**
* API: Create role
*/
public function apiCreateRole(): void
{
try {
$this->apiOrAuthRequired();
// If authenticated via session, check if admin
if (Auth::check() && !Auth::isAdmin()) {
$this->errorResponse('Acesso negado', 403);
return;
}
// If using Bearer token, allow access (API key has full access)
$name = Sanitize::string($_POST['name'] ?? '');
$description = Sanitize::string($_POST['description'] ?? '');
$permissions = $_POST['permissions'] ?? [];
if (empty($name)) {
$this->errorResponse('Nome do perfil é obrigatório', 400);
return;
}
$roleModel = new \App\Modules\Users\Models\RoleModel();
if ($roleModel->roleNameExists($name)) {
$this->errorResponse('Já existe um perfil com este nome', 409);
return;
}
$roleId = $roleModel->createRole([
'name' => $name,
'description' => $description,
'permissions' => $permissions,
'is_active' => 1
]);
if ($roleId) {
$this->successResponse([
'role_id' => $roleId
], 'Perfil criado com sucesso');
} else {
$this->errorResponse('Erro ao criar perfil', 500);
}
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_create_role']);
$this->errorResponse('Erro ao criar perfil', 500);
}
}
/**
* API: Update role
*/
public function apiUpdateRole(int $id): void
{
try {
$this->apiOrAuthRequired();
// If authenticated via session, check if admin
if (Auth::check() && !Auth::isAdmin()) {
$this->errorResponse('Acesso negado', 403);
return;
}
// If using Bearer token, allow access (API key has full access)
parse_str(file_get_contents('php://input'), $_PUT);
$name = Sanitize::string($_PUT['name'] ?? '');
$description = Sanitize::string($_PUT['description'] ?? '');
$permissions = $_PUT['permissions'] ?? [];
if (empty($name)) {
$this->errorResponse('Nome do perfil é obrigatório', 400);
return;
}
$roleModel = new \App\Modules\Users\Models\RoleModel();
if ($roleModel->roleNameExists($name, $id)) {
$this->errorResponse('Já existe outro perfil com este nome', 409);
return;
}
$success = $roleModel->updateRole($id, [
'name' => $name,
'description' => $description,
'permissions' => $permissions
]);
if ($success) {
$this->successResponse([], 'Perfil atualizado com sucesso');
} else {
$this->errorResponse('Erro ao atualizar perfil', 500);
}
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_update_role', 'role_id' => $id]);
$this->errorResponse('Erro ao atualizar perfil', 500);
}
}
/**
* API: Delete role
*/
public function apiDeleteRole(int $id): void
{
try {
$this->apiOrAuthRequired();
// If authenticated via session, check if admin
if (Auth::check() && !Auth::isAdmin()) {
$this->errorResponse('Acesso negado', 403);
return;
}
// If using Bearer token, allow access (API key has full access)
$roleModel = new \App\Modules\Users\Models\RoleModel();
// Check if role exists
$role = $roleModel->find($id);
if (!$role) {
$this->errorResponse('Perfil não encontrado', 404);
return;
}
// Prevent deletion of admin role
if ($role['name'] === 'admin' || $role['name'] === 'super_admin') {
$this->errorResponse('Não é possível eliminar o perfil de administrador', 403);
return;
}
// Check if role has users
$usersWithRole = $this->db->fetch(
"SELECT COUNT(*) as count FROM users WHERE role = ? AND is_active = 1",
[$role['name']]
);
if (($usersWithRole['count'] ?? 0) > 0) {
$this->errorResponse('Não é possível eliminar um perfil que está a ser usado por utilizadores', 409);
return;
}
$success = $roleModel->deleteRole($id);
if ($success) {
$this->successResponse([], 'Perfil eliminado com sucesso');
} else {
$this->errorResponse('Erro ao eliminar perfil', 500);
}
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'api_delete_role', 'role_id' => $id]);
$this->errorResponse('Erro ao eliminar perfil', 500);
}
}
/**
* Helper: Get role type based on name
*/
private function getRoleType(string $name): string
{
$name = strtolower($name);
if (in_array($name, ['admin', 'administrator', 'super_admin'])) {
return 'admin';
} elseif (in_array($name, ['editor', 'moderator', 'manager'])) {
return 'editor';
}
return 'user';
}
}