Files
sistema_para_juego/gallery/api/list.php

110 lines
3.3 KiB
PHP
Executable File

<?php
/**
* API de Galería - Listar imágenes
*/
header('Content-Type: application/json');
// Cargar variables de entorno
if (file_exists(__DIR__ . '/../../.env')) {
$lines = file(__DIR__ . '/../../.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) continue;
if (strpos($line, '=') === false) continue;
list($key, $value) = explode('=', $line, 2);
$_ENV[trim($key)] = trim($value);
}
}
require_once __DIR__ . '/../../shared/database/connection.php';
require_once __DIR__ . '/../../shared/auth/jwt.php';
// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado']);
exit;
}
// Permitir acceso a cualquier usuario autenticado
// Opcional: Restringir si es necesario, pero por ahora es compartido
// if (!hasPermission('editar_plantillas') && !hasPermission('crear_mensajes')) { ... }
try {
$db = getDB();
// Parámetros de paginación
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$perPage = isset($_GET['per_page']) ? min(100, max(10, intval($_GET['per_page']))) : 20;
$offset = ($page - 1) * $perPage;
// Búsqueda
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
// Construir query
$where = [];
$params = [];
if ($search) {
$where[] = "(nombre_original LIKE ? OR nombre LIKE ?)";
$params[] = "%{$search}%";
$params[] = "%{$search}%";
}
$whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';
// Contar total
$stmt = $db->prepare("SELECT COUNT(*) as total FROM gallery $whereClause");
$stmt->execute($params);
$total = $stmt->fetch()['total'];
// Obtener imágenes
$stmt = $db->prepare("
SELECT g.*, u.username
FROM gallery g
LEFT JOIN usuarios u ON g.usuario_id = u.id
$whereClause
ORDER BY g.fecha_subida DESC
LIMIT ? OFFSET ?
");
$params[] = $perPage;
$params[] = $offset;
$stmt->execute($params);
$images = $stmt->fetchAll();
// Formatear respuesta
$formattedImages = array_map(function($img) {
return [
'id' => $img['id'],
'nombre' => $img['nombre'],
'nombre_original' => $img['nombre_original'],
'url' => '/gallery/uploads/' . $img['nombre'],
'url_thumbnail' => '/gallery/thumbnails/' . $img['nombre'],
'tipo_mime' => $img['tipo_mime'],
'tamano' => $img['tamano'],
'ancho' => $img['ancho'],
'alto' => $img['alto'],
'usuario' => $img['username'],
'fecha_subida' => $img['fecha_subida']
];
}, $images);
echo json_encode([
'success' => true,
'images' => $formattedImages,
'pagination' => [
'page' => $page,
'per_page' => $perPage,
'total' => $total,
'total_pages' => ceil($total / $perPage)
]
]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'error' => 'Error del servidor']);
error_log('Error en list.php: ' . $e->getMessage());
}