//chatLog es una funcion que genera logs, agrega los detallados aca
function escribirLog(mensaje,archivo) {
if (is_object(mensaje)∣∣isarmensaje)) {
mensaje);
}
Assistant
This PHP code integrates custom REST API endpoints and AJAX functionality within a WordPress installation. Here's a breakdown of what the code does:
Log Functionality:
The escribirLog function is designed to write logs into a specified file. It supports objects and arrays by converting them to JSON.
The function also ensures the log file does not exceed 400 lines by trimming the older entries when this limit is surpassed.
chatLog is a wrapper function that specifies a particular file path for logging chat-related entries.
User
depura el codigo por favor
Assistant
r
a
y
(
mensaje=jsonencode(
code
$timestamped_log = date('Y-m-d H:i:s') . ' - ' . $mensaje;
file_put_contents($archivo, $timestamped_log . PHP_EOL, FILE_APPEND);
// Limitar el tamaño del archivo de log a 400 líneas
$line_count = count(file($archivo));
if ($line_count > 400) {
$lines = file($archivo, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$new_lines = array_slice($lines, -400);
file_put_contents($archivo, implode(PHP_EOL, $new_lines) . PHP_EOL);
}
}
function chatLog(log) {
escribirLog(log, '/var/www/wordpress/wp-content/themes/chat.log');
}
function generarToken() {
if (!is_user_logged_in()) {
wp_send_json_error('Usuario no autenticado');
}
userid=getcurrentuserid();token = wp_create_nonce('mi_chat_nonce');
wp_send_json_success(['token' => $token]);
}
function verificarToken(request) {
token = request−>getparam(′token′);user_id = wp_verify_nonce(token,′michatnuser_id) {
return new WP_REST_Response(['valid' => true, 'user_id' => $user_id], 200);
} else {
return new WP_REST_Response(['valid' => false], 401);
}
}
REST API Endpoints:
The first REST API endpoint /procesartmensaje listens for POST requests and executes the procesarMensaje callback function. It uses a token-based permission check to ensure the request's authenticity. The token is verified using wp_verify_nonce.
The second REST API endpoint /verificartoken also listens for POST requests, executing the verificarToken callback and always returns true for permission checks (this endpoint is open to all).
Token Handling with AJAX:
The generarToken function is triggered via AJAX within the WordPress environment (wp_ajax_generarToken). It first checks if the user is logged in, then generates a nonce token specific to the current user session and returns it in a JSON response.
The verificarToken function verifies the token submitted in a request to ensure it is valid. If the token is valid, it returns a REST response with user validation data. If not, it returns a response indicating the token is invalid.
Overall, this implementation provides a secure way to handle user-specific token generation and verification, suitable for a chat application or similar feature within WordPress. The logs provide an audit trail for chat messages, with file size management to prevent excessive growth.
Claro, vamos a limpiar y organizar un poco el código. Aquí tienes una versión depurada:
php
<?php
// Función para escribir logs
function escribirLog($mensaje, $archivo) {
if (is_object($mensaje) || is_array($mensaje)) {
$mensaje = json_encode($mensaje);
}
$timestamped_log = date('Y-m-d H:i:s') . ' - ' . $mensaje;
file_put_contents($archivo, $timestamped_log . PHP_EOL, FILE_APPEND);
// Limitar el tamaño del archivo de log a 400 líneas
$lines = file($archivo, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (count($lines) > 400) {
$new_lines = array_slice($lines, -400);
file_put_contents($archivo, implode(PHP_EOL, $new_lines) . PHP_EOL);
}
}
// Función para registrar un log en el archivo de chat.log
function chatLog($log) {
escribirLog($log, '/var/www/wordpress/wp-content/themes/chat.log');
}
// Registrar endpoint para procesar mensaje
add_action('rest_api_init', function () {
register_rest_route('galle/v2', '/procesartmensaje', array(
'methods' => 'POST',
'callback' => 'procesarMensaje',
'permission_callback' => function ($request) {
$token = $request->get_header('X-WP-Nonce');
return wp_verify_nonce($token, 'mi_chat_nonce');
}
));
});
// Registrar endpoint para verificar token
add_action('rest_api_init', function () {
register_rest_route('galle/v2', '/verificartoken', array(
'methods' => 'POST',
'callback' => 'verificarToken',
'permission_callback' => '__return_true'
));
});
// Acción AJAX para generar token
add_action('wp_ajax_generarToken', 'generarToken');
function generarToken() {
if (!is_user_logged_in()) {
wp_send_json_error('Usuario no autenticado');
}
$token = wp_create_nonce('mi_chat_nonce');
wp_send_json_success(['token' => $token]);
}
function verificarToken($request) {
$token = $request->get_param('token');
$user_id = wp_verify_nonce($token, 'mi_chat_nonce');
if ($user_id) {
return new WP_REST_Response(['valid' => true, 'user_id' => $user_id], 200);
} else {
return new WP_REST_Response(['valid' => false], 401);
}
}
?>
Cambios Realizados:
Comentarios: Añadidos y mejorados para una mejor comprensión de cada bloque de código.
Condicional de Límite de Líneas del Log: Mejorada la lógica para siempre leer las líneas del archivo y ajustar el contenido si es necesario, utilizando file y array_slice.
Organización: Asegurado de que la función y las declaraciones de acción estén claramente separadas y bien documentadas.
Seguridad y Limpieza: Confirmación de que no hay fugas de datos innecesarios y manejo seguro de tokens y sesiones.
Este código ahora está mejor estructurado y comentado para facilitar su mantenimiento y comprensión.