- Create UserActivitiesTable migration for tracking user activities - Create UserActivityModel for managing activity data - Replace mock data in apiGetRecentActivity with real database data - Remove all mock/fake data from the project
960 lines
36 KiB
PHP
960 lines
36 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 usando 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 {
|
|
// Check if user is logged in and is admin, or if using API key
|
|
$isLoggedIn = Auth::check();
|
|
$isAdmin = $isLoggedIn && Auth::isAdmin();
|
|
$hasApiKey = !empty($_SERVER['HTTP_AUTHORIZATION']) &&
|
|
stripos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer ') === 0;
|
|
|
|
if (!$isAdmin && !$hasApiKey) {
|
|
http_response_code(403);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['error' => '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)));
|
|
|
|
$users = $this->userModel->getAllForAdmin($search, $sort, $page, $perPage);
|
|
$totalUsers = $this->userModel->getTotalForAdmin($search);
|
|
$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: Get single user by ID
|
|
*/
|
|
public function apiGetUser(int $id): void
|
|
{
|
|
try {
|
|
$this->requireAuth();
|
|
|
|
if (!Auth::isAdmin()) {
|
|
http_response_code(403);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['error' => '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 {
|
|
$this->requireAuth();
|
|
|
|
if (!Auth::isAdmin()) {
|
|
http_response_code(403);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['error' => '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 {
|
|
$this->requireAuth();
|
|
|
|
if (!Auth::isAdmin()) {
|
|
http_response_code(403);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['error' => '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 {
|
|
$this->requireAuth();
|
|
|
|
if (!Auth::isAdmin()) {
|
|
http_response_code(403);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['error' => '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';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* API: Get recent activity
|
|
*/
|
|
public function apiGetRecentActivity(): void
|
|
{
|
|
try {
|
|
// Check if user is logged in and is admin, or if using API key
|
|
$isLoggedIn = Auth::check();
|
|
$isAdmin = $isLoggedIn && Auth::isAdmin();
|
|
$hasApiKey = !empty($_SERVER['HTTP_AUTHORIZATION']) &&
|
|
stripos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer ') === 0;
|
|
|
|
if (!$isAdmin && !$hasApiKey) {
|
|
http_response_code(403);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['error' => 'Acesso negado']);
|
|
exit;
|
|
}
|
|
|
|
// Get real activity data from database
|
|
$activityModel = new \App\Modules\Users\Models\UserActivityModel();
|
|
$activities = $activityModel->getAllRecentActivities(50);
|
|
|
|
header('Content-Type: application/json');
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $activities
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'api_get_recent_activity']);
|
|
http_response_code(500);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['error' => 'Erro interno do servidor']);
|
|
}
|
|
exit;
|
|
}
|
|
}
|