false, 'message' => $post_data->get_error_message(), ], 400); } // Añadimos el nombre del endpoint solicitado $post_data['endpoint'] = $endpoint_name; if ($endpoint_name === 'secciones') { $post_data['categorias_wp'] = aife_get_categorias_con_ruta(); } // Endpoint específico para autor if ($params['endpoint'] === 'autor') { return aife_generar_autor($params); } // Endpoint específico para imagen if ($params['endpoint'] === 'imagen') { return aife_generar_imagen($params); } // Endpoint específico para importación if ($endpoint_name === 'importacion') { return aife_procesar_importacion_post_final($params); } $response = wp_remote_post('https://openai.editmaker.com/wp/api/endpoints_aifeeds.php', [ 'headers' => ['Content-Type' => 'application/json', 'Referer' => home_url()], 'body' => wp_json_encode($post_data), 'timeout' => 120 ]); if (is_wp_error($response)) { return new WP_REST_Response([ 'success' => false, 'message' => __('Error en la llamada a openai.editmaker.com: ', 'ai-feeds') . $response->get_error_message(), ], 500); } $body = wp_remote_retrieve_body($response); $resultado = json_decode($body, true); // Agrega claramente esto para capturar una respuesta inesperada if (empty($resultado) || !isset($resultado['success'])) { return new WP_REST_Response([ 'success' => false, 'message' => 'Respuesta inesperada o vacía desde el servidor intermedio.', 'raw_body' => $body ], 500); } if ($endpoint_name === 'refrito' && $resultado['success'] && isset($resultado['data']['refrito'])) { // Eliminar imagen destacada claramente (función ya existente) $resultado['data']['refrito'] = aife_eliminar_imagen_destacada_del_refrito( $resultado['data']['refrito'], $params['post_id'] ); $deleteLinks = (bool)aife_obtenerConfig($post_id, 'deleteLinks'); $nofollow = (bool)aife_obtenerConfig($post_id, 'nofollow'); // Evaluar claramente deleteLinks if ($deleteLinks) { $resultado['data']['refrito'] = aife_remove_links($resultado['data']['refrito']); } // Evaluar claramente nofollow si deleteLinks está desactivado else if ($nofollow) { $resultado['data']['refrito'] = aife_add_nofollow_links($resultado['data']['refrito']); } } return new WP_REST_Response([ 'success' => true, 'resultado' => $resultado, ], 200); } /** * Registra los endpoints REST personalizados. */ add_action('rest_api_init', 'aife_register_endpoints'); function aife_register_endpoints() { register_rest_route('ai-feeds/v1', '/procesar', [ 'methods' => 'POST', 'callback' => 'aife_endpoint_handler', 'permission_callback' => function () { return current_user_can('edit_posts'); } ]); } function aife_endpoint_handler(WP_REST_Request $request) { $params = $request->get_json_params(); if (empty($params['endpoint'])) { return new WP_REST_Response([ 'success' => false, 'message' => __('Falta el parámetro endpoint.', 'ai-feeds'), ], 400); } return aife_procesar_endpoint($params, sanitize_text_field($params['endpoint'])); } add_action('rest_api_init', function () { register_rest_route('ai-feeds/v1', '/check-tags', [ 'methods' => 'POST', 'callback' => 'aife_check_existing_tags', 'permission_callback' => function() { return current_user_can('edit_posts'); } ]); }); function aife_check_existing_tags(WP_REST_Request $request) { $tags = $request->get_param('tags'); if (empty($tags) || !is_array($tags)) { return new WP_REST_Response(['success' => false, 'existing_tags' => []], 400); } $existing = []; foreach ($tags as $tag) { if (term_exists($tag, 'post_tag')) { $existing[] = $tag; } } return new WP_REST_Response(['success' => true, 'existing_tags' => $existing], 200); } function aife_obtenerConfig($post_id, $key, $default = null) { $config = aife_get_config_feed_y_general_from_aife_original_id($post_id); $config_feed = $config['config_feed'] ?? []; $config_general = $config['config_general'] ?? []; // ¿Usa la configuración general? $usa_config_general = !empty($config_feed['_aife_hereda_ajustes']); // Comprobar si existe una configuración específica para el feed if (!$usa_config_general && array_key_exists($key, $config_feed)) { return $config_feed[$key]; } // Si no tiene específica o hereda, comprobar configuración general if (array_key_exists($key, $config_general)) { return $config_general[$key]; } // Si no existe ninguna configuración, devolver valor por defecto return $default; } /** * Obtiene claramente el ID del firmante según configuración general o específica del feed. * * @param int $post_id * @return int ID del usuario firmante o -1 si no está definido. */ function aife_obtenerFirmanteSegunConfig($post_id): int { $firmante = aife_obtenerConfig($post_id, 'firmante', -1); return (int) $firmante; } function aife_generar_imagen($params) { $post_id = $params['post_id']; $es_url_valida = function($url) { return filter_var($url, FILTER_VALIDATE_URL) && preg_match('/^https?:\/\//', $url); }; // Intenta obtener primero de metas $thumbnail_url = get_post_meta($post_id, '_thumbnail_url', true); $enclosure_url = get_post_meta($post_id, '_enclosure', true); $imagen_final = $thumbnail_url ?: $enclosure_url; // Si no hay una URL válida, buscar en el contenido if ($es_url_valida($thumbnail_url)) { $imagen_final = $thumbnail_url; } elseif ($es_url_valida($enclosure_url)) { $imagen_final = $enclosure_url; } else { $imagen_final = ''; } $alt = ''; $title = ''; // Si no se encontró imagen en metas, buscar claramente en el contenido if (!$imagen_final) { $post = get_post($post_id); if ($post && preg_match('/]+src=["\']([^"\']+)["\'][^>]*>/i', $post->post_content, $matches)) { $imagen_final = $matches[1]; // Capturar alt claramente preg_match('/alt=["\']([^"\']*)["\']/i', $matches[0], $alt_match); $alt = !empty($alt_match[1]) ? $alt_match[1] : ''; // Capturar title claramente preg_match('/title=["\']([^"\']*)["\']/i', $matches[0], $title_match); $title = !empty($title_match[1]) ? $title_match[1] : ''; } } if (!$imagen_final) { return new WP_REST_Response([ 'success' => true, 'resultado' => [ 'success' => true, 'warning_code' => 'DISABLED', 'mensaje' => 'No se encontró ninguna imagen en el feed.', 'data' => ['html' => ''] ] ], 200); } // Devuelve HTML enriquecido con alt y title claramente ob_start(); ?>
<?php echo esc_attr($alt ?: 'Imagen destacada'); ?>title="" >
alt ➡️
title ➡️
true, 'resultado' => [ 'success' => true, 'mensaje' => 'Imagen destacada obtenida correctamente.', 'data' => [ 'html' => ob_get_clean(), 'imagen_destacada' => $imagen_final, 'alt' => $alt, 'title' => $title ] ] ], 200); } /** * Elimina la imagen destacada del HTML del refrito si está presente. * * @param string $refrito_html HTML del refrito generado. * @param int $post_id ID del post original. * @return string HTML ajustado sin la imagen destacada. */ function aife_eliminar_imagen_destacada_del_refrito(string $refrito_html, int $post_id): string { // Genera claramente la imagen destacada del post $imagen_response = aife_generar_imagen(['post_id' => $post_id]); $imagen_data = $imagen_response->get_data(); if (!empty($imagen_data['resultado']['data']['imagen_destacada'])) { $imagen_destacada_url = $imagen_data['resultado']['data']['imagen_destacada']; $imagen_destacada_url_escaped = preg_quote($imagen_destacada_url, '/'); // Elimina claramente la imagen destacada del HTML del refrito $refrito_html = preg_replace( '/]+src=["\']' . $imagen_destacada_url_escaped . '["\'][^>]*>/i', '', $refrito_html ); } return $refrito_html; } function aife_generar_autor(array $params) { $post_id = $params['post_id']; // Obtienes el autor (firmante) según tu lógica actual $autor_id = aife_obtenerFirmanteSegunConfig($post_id); // ← función que te devuelve claramente el ID del usuario if($autor_id < 1){ return new WP_REST_Response([ 'success' => true, 'resultado' => [ 'success' => true, 'warning_code' => 'DISABLED', 'mensaje' => 'No se configuró autor.', 'data' => [ 'autor' => '' ] ] ], 200); } ob_start(); // captura el HTML claramente ?> true, 'resultado' => [ 'success' => true, 'mensaje' => 'Tarjeta de autor generada correctamente.', 'data' => [ 'autor' => $html_autor, 'autor_id' => $autor_id ] ] ], 200); }