up
This commit is contained in:
@@ -58,13 +58,17 @@ try {
|
||||
message_type,
|
||||
content,
|
||||
media_url,
|
||||
local_file,
|
||||
local_thumb,
|
||||
filename,
|
||||
mime_type,
|
||||
status,
|
||||
created_at
|
||||
FROM conversations
|
||||
WHERE user_id = ?
|
||||
AND (
|
||||
message_type = 'text'
|
||||
OR (message_type IN ('image', 'audio', 'video', 'document') AND media_url IS NOT NULL AND media_url != '')
|
||||
OR (message_type IN ('image', 'audio', 'video', 'document', 'sticker') AND (media_url IS NOT NULL AND media_url != '' OR local_file IS NOT NULL AND local_file != ''))
|
||||
)
|
||||
ORDER BY created_at ASC",
|
||||
[$user_id]
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Obtener estadísticas de Rate Limiting de Facebook
|
||||
* Fecha: 6 de febrero de 2026
|
||||
*/
|
||||
|
||||
// Configurar manejo de errores
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
||||
// Cargar config primero (ya incluye el autoloader)
|
||||
require_once __DIR__ . '/../config/config.php';
|
||||
|
||||
// Verificar que la clase exista antes de usarla
|
||||
if (!class_exists('RateLimitMonitor')) {
|
||||
$rateLimitMonitorPath = __DIR__ . '/../services/RateLimitMonitor.php';
|
||||
if (file_exists($rateLimitMonitorPath)) {
|
||||
require_once $rateLimitMonitorPath;
|
||||
} else {
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
http_response_code(500);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'RateLimitMonitor service not found',
|
||||
'path_checked' => $rateLimitMonitorPath
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
// Requerir autenticación
|
||||
requireAuthentication();
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET');
|
||||
header('Access-Control-Allow-Headers: Content-Type');
|
||||
|
||||
try {
|
||||
$monitor = new RateLimitMonitor();
|
||||
|
||||
$action = $_GET['action'] ?? 'current';
|
||||
|
||||
switch ($action) {
|
||||
case 'current':
|
||||
// Obtener estadísticas actuales
|
||||
$stats = $monitor->getCurrentStats();
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'data' => $stats,
|
||||
'timestamp' => time(),
|
||||
'datetime' => date('Y-m-d H:i:s')
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'history':
|
||||
// Obtener historial
|
||||
$type = $_GET['type'] ?? 'app';
|
||||
$limit = min(100, intval($_GET['limit'] ?? 20));
|
||||
|
||||
$history = $monitor->getUsageHistory($type, $limit);
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'data' => $history,
|
||||
'type' => $type,
|
||||
'count' => count($history)
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'cleanup':
|
||||
// Ejecutar limpieza (solo admin)
|
||||
$monitor->cleanup();
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Limpieza completada'
|
||||
]);
|
||||
break;
|
||||
|
||||
default:
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'Acción no válida. Use: current, history, cleanup'
|
||||
]);
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
http_response_code(500);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
@@ -93,6 +93,7 @@ header('Content-Type: application/json; charset=utf-8');
|
||||
$mediaId = $_GET['id'] ?? $_POST['id'] ?? null;
|
||||
$providedUrl = $_GET['url'] ?? $_POST['url'] ?? null;
|
||||
$download = isset($_GET['download']) && $_GET['download'] === '1';
|
||||
$debug = isset($_GET['debug']) && $_GET['debug'] === '1';
|
||||
|
||||
if (!$mediaId && !$providedUrl) {
|
||||
http_response_code(400);
|
||||
@@ -239,6 +240,112 @@ if ($providedUrl) {
|
||||
}
|
||||
}
|
||||
|
||||
// === MODO DEBUG: muestra diagnóstico en lugar de redirigir/descargar ===
|
||||
if ($debug) {
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
$tokenRaw = getConfigFromDB('whatsapp_token', '');
|
||||
$tokenPreview = $tokenRaw ? substr($tokenRaw, 0, 15) . '...' . substr($tokenRaw, -10) : '(vacío)';
|
||||
$apiUrlConfig = rtrim(getConfigFromDB('whatsapp_api_url', 'https://graph.facebook.com/v22.0/'), '/');
|
||||
|
||||
echo '<html><head><title>Media URL Debug</title>';
|
||||
echo '<style>body{font-family:monospace;padding:20px;background:#1e1e1e;color:#d4d4d4}';
|
||||
echo '.ok{color:#4ec9b0}.err{color:#f44747}.warn{color:#dcdcaa}';
|
||||
echo 'pre{background:#2d2d2d;padding:15px;border-radius:5px;overflow-x:auto;white-space:pre-wrap}';
|
||||
echo 'h2{color:#569cd6}h3{color:#9cdcfe}</style></head><body>';
|
||||
echo '<h2>🔍 Diagnóstico media-url.php</h2>';
|
||||
echo '<h3>Parámetros de entrada</h3><pre>';
|
||||
echo "Media ID: " . htmlspecialchars($mediaId ?? '(no proporcionado)') . "\n";
|
||||
echo "URL proporcionada: " . htmlspecialchars($providedUrl ?? '(no proporcionada)') . "\n";
|
||||
echo "download: " . ($download ? '1' : '0') . "\n";
|
||||
echo '</pre>';
|
||||
|
||||
echo '<h3>Configuración</h3><pre>';
|
||||
echo "Token: " . htmlspecialchars($tokenPreview) . "\n";
|
||||
echo "API URL: " . htmlspecialchars($apiUrlConfig) . "\n";
|
||||
|
||||
if (empty($tokenRaw)) {
|
||||
echo '<span class="err">⛔ ERROR: Token de WhatsApp vacío o no configurado</span>' . "\n";
|
||||
echo 'Solución: Configurar en /configurar_whatsapp.php o en system_config (key: whatsapp_token)' . "\n";
|
||||
} else {
|
||||
echo '<span class="ok">✅ Token presente</span>' . "\n";
|
||||
}
|
||||
echo '</pre>';
|
||||
|
||||
echo '<h3>Resultado Graph API</h3><pre>';
|
||||
if ($mediaUrl) {
|
||||
echo '<span class="ok">✅ URL resuelta:</span> ' . htmlspecialchars($mediaUrl) . "\n";
|
||||
echo "Resuelto desde Graph: " . ($resolvedFromGraph ? 'Sí' : 'No') . "\n";
|
||||
|
||||
// Validar que la URL sea accesible desde el servidor
|
||||
echo "\n<span class=\"warn\">Verificando accesibilidad de la URL...</span>\n";
|
||||
$testCh = curl_init();
|
||||
$testHeaders = ['User-Agent: WhatsAppMediaProxy/1.0', 'Accept: */*'];
|
||||
if ($tokenRaw) $testHeaders[] = 'Authorization: Bearer ' . $tokenRaw;
|
||||
curl_setopt_array($testCh, [
|
||||
CURLOPT_URL => $mediaUrl,
|
||||
CURLOPT_NOBODY => true,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_HTTPHEADER => $testHeaders,
|
||||
]);
|
||||
curl_exec($testCh);
|
||||
$testInfo = curl_getinfo($testCh);
|
||||
$testErr = curl_error($testCh);
|
||||
curl_close($testCh);
|
||||
|
||||
echo "HTTP Status: " . ($testInfo['http_code'] ?? 'N/A') . "\n";
|
||||
echo "Content-Type: " . ($testInfo['content_type'] ?? 'N/A') . "\n";
|
||||
echo "Content-Length: " . ($testInfo['download_content_length'] ?? 'N/A') . " bytes\n";
|
||||
|
||||
if ($testErr) {
|
||||
echo '<span class="err">⛔ Error cURL: ' . htmlspecialchars($testErr) . '</span>' . "\n";
|
||||
}
|
||||
|
||||
if (($testInfo['http_code'] ?? 0) >= 400) {
|
||||
echo '<span class="err">⛔ La URL del media NO es accesible (HTTP ' . $testInfo['http_code'] . ')</span>' . "\n";
|
||||
if (($testInfo['http_code'] ?? 0) == 404) {
|
||||
echo '<span class="warn">⚠️ El media probablemente expiró. Los archivos multimedia de WhatsApp expiran después de ~30 días.</span>' . "\n";
|
||||
} elseif (($testInfo['http_code'] ?? 0) == 401 || ($testInfo['http_code'] ?? 0) == 403) {
|
||||
echo '<span class="warn">⚠️ Error de autenticación. Verificar que el token sea válido y tenga permisos.</span>' . "\n";
|
||||
}
|
||||
} else {
|
||||
echo '<span class="ok">✅ URL accesible correctamente</span>' . "\n";
|
||||
}
|
||||
} else {
|
||||
echo '<span class="err">⛔ No se pudo resolver la URL del media</span>' . "\n";
|
||||
if (!empty($decoded)) {
|
||||
echo "Respuesta de Graph API:\n";
|
||||
echo htmlspecialchars(json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) . "\n";
|
||||
|
||||
// Diagnóstico específico de errores comunes
|
||||
$errCode = $decoded['error']['code'] ?? null;
|
||||
$errSubcode = $decoded['error']['error_subcode'] ?? null;
|
||||
$errMsg = $decoded['error']['message'] ?? '';
|
||||
|
||||
if ($errCode == 190) {
|
||||
echo '<span class="err">⛔ Token expirado o inválido (code 190)</span>' . "\n";
|
||||
echo '<span class="warn">Solución: Renovar el token en /configurar_whatsapp.php</span>' . "\n";
|
||||
} elseif ($errCode == 100 && $errSubcode == 33) {
|
||||
echo '<span class="err">⛔ Media ID no encontrado o expirado</span>' . "\n";
|
||||
echo '<span class="warn">Los archivos multimedia de WhatsApp Business API expiran aproximadamente 30 días después de ser recibidos.</span>' . "\n";
|
||||
} elseif ($errCode == 100) {
|
||||
echo '<span class="err">⛔ Parámetro inválido (code 100)</span>' . "\n";
|
||||
echo '<span class="warn">El media ID puede ser incorrecto: ' . htmlspecialchars($mediaId ?? '') . '</span>' . "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
echo '</pre>';
|
||||
|
||||
echo '<h3>Respuesta raw de Graph API ($decoded)</h3><pre>';
|
||||
echo htmlspecialchars(json_encode($decoded ?? null, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
echo '</pre>';
|
||||
|
||||
echo '<p style="margin-top:20px;color:#888">Generado: ' . date('Y-m-d H:i:s T') . '</p>';
|
||||
echo '</body></html>';
|
||||
exit;
|
||||
}
|
||||
|
||||
// Soporte para archivos locales (local=uploads/media/...)
|
||||
$local = $_GET['local'] ?? null;
|
||||
if ($local) {
|
||||
|
||||
@@ -414,3 +414,15 @@
|
||||
[2026-02-03 20:31:47] Graph API request to https://graph.facebook.com/v22.0/1217156256734654
|
||||
[2026-02-03 20:31:48] Proxying Facebook media URL with Authorization to https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=1217156256734654&source=getMedia&ext=1770169008&hash=ARmSF2NK4GqmW53yaJd3NCLYub_AGbau7EHf5WOOETVxbw
|
||||
[2026-02-03 20:31:48] Resolved media URL from Graph for mid 2371342336638440: https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=2371342336638440&source=getMedia&ext=1770169008&hash=ARlAZuDk9UsmFsMvn4qiAOOAk45RwETVe04h9vkJdDruXg
|
||||
[2026-02-20 09:02:34] Request: GET /api/version/media-url.php?id=1307493841213652&debug=1 GET:{"id":"1307493841213652","debug":"1"} POST:[]
|
||||
[2026-02-20 09:02:34] Graph API request to https://graph.facebook.com/v22.0/1307493841213652
|
||||
[2026-02-20 09:03:08] Request: GET /api/version/media-url.php?id=1217156256734654 GET:{"id":"1217156256734654"} POST:[]
|
||||
[2026-02-20 09:03:08] Graph API request to https://graph.facebook.com/v22.0/1217156256734654
|
||||
[2026-02-20 09:03:10] Request: GET /api/version/media-url.php?url=https%3A%2F%2Flookaside.fbsbx.com%2Fwhatsapp_business%2Fattachments%2F%3Fmid%3D2371342336638440%26source%3Dwebhook%26ext%3D1769575796%26hash%3DARndVKdw1p0CCx3_DpTblR2aOVkb_W5mbTqGFPSOK77cjA GET:{"url":"https:\/\/lookaside.fbsbx.com\/whatsapp_business\/attachments\/?mid=2371342336638440&source=webhook&ext=1769575796&hash=ARndVKdw1p0CCx3_DpTblR2aOVkb_W5mbTqGFPSOK77cjA"} POST:[]
|
||||
[2026-02-20 09:03:10] Graph API fetch failed for mid 2371342336638440 - http: 400 - err: - resp: {"error":{"message":"Unsupported get request. Object with ID '2371342336638440' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api","type":"GraphMethodException","code":100,"error_subcode":33,"fbtrace_id":"AdhQHtrZK9AxINPUaZhSBxG"}}
|
||||
[2026-02-20 09:03:10] Proxying Facebook media URL with Authorization to https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=2371342336638440&source=webhook&ext=1769575796&hash=ARndVKdw1p0CCx3_DpTblR2aOVkb_W5mbTqGFPSOK77cjA
|
||||
[2026-02-20 09:05:33] Request: GET /api/version/media-url.php?id=1217156256734654 GET:{"id":"1217156256734654"} POST:[]
|
||||
[2026-02-20 09:05:33] Graph API request to https://graph.facebook.com/v22.0/1217156256734654
|
||||
[2026-02-20 09:05:37] Request: GET /api/version/media-url.php?url=https%3A%2F%2Flookaside.fbsbx.com%2Fwhatsapp_business%2Fattachments%2F%3Fmid%3D2371342336638440%26source%3Dwebhook%26ext%3D1769575796%26hash%3DARndVKdw1p0CCx3_DpTblR2aOVkb_W5mbTqGFPSOK77cjA GET:{"url":"https:\/\/lookaside.fbsbx.com\/whatsapp_business\/attachments\/?mid=2371342336638440&source=webhook&ext=1769575796&hash=ARndVKdw1p0CCx3_DpTblR2aOVkb_W5mbTqGFPSOK77cjA"} POST:[]
|
||||
[2026-02-20 09:05:37] Graph API fetch failed for mid 2371342336638440 - http: 400 - err: - resp: {"error":{"message":"Unsupported get request. Object with ID '2371342336638440' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api","type":"GraphMethodException","code":100,"error_subcode":33,"fbtrace_id":"Ayy1xE4nFVa4ae3yKVwTCJo"}}
|
||||
[2026-02-20 09:05:37] Proxying Facebook media URL with Authorization to https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=2371342336638440&source=webhook&ext=1769575796&hash=ARndVKdw1p0CCx3_DpTblR2aOVkb_W5mbTqGFPSOK77cjA
|
||||
|
||||
@@ -10,3 +10,11 @@
|
||||
[21-Jan-2026 21:55:38 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 522
|
||||
[21-Jan-2026 21:59:30 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 203
|
||||
[21-Jan-2026 21:59:30 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 522
|
||||
[20-Feb-2026 09:02:34 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 220
|
||||
[20-Feb-2026 09:02:35 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 295
|
||||
[20-Feb-2026 09:03:09 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 220
|
||||
[20-Feb-2026 09:03:10 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 159
|
||||
[20-Feb-2026 09:03:10 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 645
|
||||
[20-Feb-2026 09:05:33 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 220
|
||||
[20-Feb-2026 09:05:37 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 159
|
||||
[20-Feb-2026 09:05:37 America/Bogota] PHP Deprecated: Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Users/lizandro/Documents/GitHub/whatsapp/api/version/media-url.php on line 645
|
||||
|
||||
+55
-1
@@ -209,12 +209,54 @@ class WhatsAppWebhook {
|
||||
$mimeType = $message['document']['mime_type'] ?? null;
|
||||
$filename = $message['document']['filename'] ?? null;
|
||||
|
||||
// Do NOT download documents automatically; keep media id so browser will redirect and download
|
||||
}
|
||||
|
||||
// Log debug (temporal) para verificar cómo llegan media_url/filename
|
||||
error_log(sprintf('[webhook] messageId=%s type=%s mediaUrl=%s filename=%s mime=%s', $messageId, $messageType, $mediaUrl ?? 'NULL', $filename ?? 'NULL', $mimeType ?? 'NULL'));
|
||||
|
||||
// ── Descargar media localmente de inmediato ──
|
||||
// Si hay un media ID (numérico) o URL de Graph, descargarlo y guardarlo en uploads/media/
|
||||
$localFile = null;
|
||||
$localThumb = null;
|
||||
if (!empty($mediaUrl) && in_array($messageType, ['image', 'audio', 'video', 'document', 'sticker'])) {
|
||||
try {
|
||||
$mediaService = new MediaService();
|
||||
$subdir = date('Y/m'); // Organizar por año/mes
|
||||
|
||||
// Determinar si es un media ID (numérico) o una URL directa
|
||||
if (preg_match('/^\d+$/', $mediaUrl)) {
|
||||
// Es un media ID de WhatsApp → resolver vía Graph API y descargar
|
||||
$stored = $mediaService->fetchAndStoreFromGraph($mediaUrl, $subdir);
|
||||
} else {
|
||||
// Es una URL directa → descargar directamente
|
||||
$stored = $mediaService->fetchAndStoreFromUrl($mediaUrl, $subdir);
|
||||
}
|
||||
|
||||
if (!empty($stored['local_file'])) {
|
||||
$localFile = $stored['local_file'];
|
||||
error_log("[webhook] Media descargado localmente: {$localFile}");
|
||||
}
|
||||
if (!empty($stored['local_thumb'])) {
|
||||
$localThumb = $stored['local_thumb'];
|
||||
}
|
||||
} catch (Exception $mediaEx) {
|
||||
error_log("[webhook] Error descargando media (se encolará para retry): " . $mediaEx->getMessage());
|
||||
// Encolar en media_queue para reintento posterior
|
||||
try {
|
||||
$this->db->insert('media_queue', [
|
||||
'media_id' => preg_match('/^\d+$/', $mediaUrl) ? $mediaUrl : '',
|
||||
'media_url' => $mediaUrl,
|
||||
'subdir' => date('Y/m'),
|
||||
'status' => 'pending',
|
||||
'created_at' => date('Y-m-d H:i:s')
|
||||
]);
|
||||
error_log("[webhook] Media encolado en media_queue para retry");
|
||||
} catch (Exception $qEx) {
|
||||
error_log("[webhook] Error encolando media: " . $qEx->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Guardar mensaje en base de datos
|
||||
$saveData = [
|
||||
'user_id' => $user['id'],
|
||||
@@ -291,6 +333,18 @@ class WhatsAppWebhook {
|
||||
// Guardar mensaje y conservar el id de la conversación para posibles encolamientos
|
||||
$conversationId = $this->saveMessage($saveData);
|
||||
|
||||
// Si el media se encoló (no se pudo descargar), actualizar media_queue con el conversation_id
|
||||
if (!empty($mediaUrl) && empty($localFile) && in_array($messageType, ['image', 'audio', 'video', 'document', 'sticker'])) {
|
||||
try {
|
||||
$this->db->query(
|
||||
"UPDATE media_queue SET conversation_id = :cid WHERE media_id = :mid AND conversation_id IS NULL ORDER BY id DESC LIMIT 1",
|
||||
['cid' => $conversationId, 'mid' => (preg_match('/^\d+$/', $mediaUrl) ? $mediaUrl : '')]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
error_log("[webhook] Error actualizando media_queue con conversation_id: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Crear notificación para UI (nuevo mensaje entrante)
|
||||
try {
|
||||
$this->db->insert('notifications', [
|
||||
|
||||
Reference in New Issue
Block a user