false, 'error' => 'Método no permitido']); exit; } try { // Verificar que se subió un archivo if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) { throw new Exception('No se recibió ningún archivo o hubo un error en la carga'); } $file = $_FILES['file']; $fileSize = $file['size']; $fileName = basename($file['name']); $fileTmpPath = $file['tmp_name']; $fileType = $file['type']; // Validar tamaño según tipo $maxSize = 16 * 1024 * 1024; // 16MB por defecto if (strpos($fileType, 'image/') === 0) { $maxSize = 5 * 1024 * 1024; // 5MB para imágenes } elseif (strpos($fileType, 'application/') === 0) { $maxSize = 100 * 1024 * 1024; // 100MB para documentos } if ($fileSize > $maxSize) { throw new Exception('El archivo es demasiado grande. Máximo: ' . ($maxSize / 1024 / 1024) . 'MB'); } // Validar tipos de archivo permitidos $allowedTypes = [ // Imágenes 'image/jpeg', 'image/jpg', 'image/png', 'image/webp', // Videos 'video/mp4', 'video/3gpp', 'video/quicktime', // Audios 'audio/aac', 'audio/mp3', 'audio/mpeg', 'audio/ogg', 'audio/amr', 'audio/webm', // Documentos 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation' ]; if (!in_array($fileType, $allowedTypes)) { throw new Exception('Tipo de archivo no permitido: ' . $fileType); } // Crear directorio de uploads si no existe $uploadDir = __DIR__ . '/../uploads/'; if (!is_dir($uploadDir)) { mkdir($uploadDir, 0755, true); } // Generar nombre único $extension = pathinfo($fileName, PATHINFO_EXTENSION); $uniqueName = uniqid('media_', true) . '.' . $extension; $uploadPath = $uploadDir . $uniqueName; // Mover archivo if (!move_uploaded_file($fileTmpPath, $uploadPath)) { throw new Exception('Error al guardar el archivo en el servidor'); } // Si es audio WebM, intentar convertir a OGG/Opus (formatos más compatibles con WhatsApp) if (strpos($fileType, 'audio/webm') === 0) { $ffmpeg = trim(@shell_exec('which ffmpeg 2>/dev/null')); if ($ffmpeg) { $convertedName = uniqid('media_', true) . '.ogg'; $convertedPath = $uploadDir . $convertedName; // Convertir a Opus (bitrate moderado) $cmd = escapeshellcmd($ffmpeg) . ' -y -i ' . escapeshellarg($uploadPath) . ' -c:a libopus -b:a 64000 ' . escapeshellarg($convertedPath) . ' 2>&1'; $out = shell_exec($cmd); if (file_exists($convertedPath) && filesize($convertedPath) > 0) { // Reemplazar archivo original por el convertido @unlink($uploadPath); $uploadPath = $convertedPath; $uniqueName = $convertedName; $fileType = 'audio/ogg'; error_log('upload_media.php - Audio convertido a OGG/Opus: ' . $convertedName); error_log('upload_media.php - ffmpeg output: ' . substr($out, 0, 2000)); } else { error_log('upload_media.php - Falló conversión con ffmpeg. Output: ' . substr($out, 0, 2000)); } } else { error_log('upload_media.php - ffmpeg no encontrado, no se puede convertir audio/webm.'); } } // Construir URL pública $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http'; $host = $_SERVER['HTTP_HOST']; $publicUrl = $protocol . '://' . $host . '/uploads/' . $uniqueName; // Determinar tipo de medio $mediaType = 'document'; if (strpos($fileType, 'image/') === 0) { $mediaType = 'image'; } elseif (strpos($fileType, 'video/') === 0) { $mediaType = 'video'; } elseif (strpos($fileType, 'audio/') === 0) { $mediaType = 'audio'; } // Guardar información en base de datos (opcional) $db = Database::getInstance(); $mediaId = $db->insert('media_files', [ 'filename' => $fileName, 'unique_name' => $uniqueName, 'file_type' => $fileType, 'file_size' => $fileSize, 'media_type' => $mediaType, 'file_path' => $uploadPath, 'public_url' => $publicUrl, 'uploaded_by' => $_SESSION['user']['id'] ?? null, 'created_at' => date('Y-m-d H:i:s') ]); echo json_encode([ 'success' => true, 'message' => 'Archivo subido correctamente', 'id' => $mediaId, 'filename' => $fileName, 'public_url' => $publicUrl, 'media_type' => $mediaType, 'mime_type' => $fileType, 'size' => $fileSize, // Mantener compatibilidad con código existente 'data' => [ 'id' => $mediaId, 'filename' => $fileName, 'url' => $publicUrl, 'type' => $mediaType, 'mime_type' => $fileType, 'size' => $fileSize ] ]); } catch (Exception $e) { error_log("Error en upload_media.php: " . $e->getMessage()); http_response_code(500); echo json_encode([ 'success' => false, 'error' => $e->getMessage() ]); } ?>