| 1 |
<?php |
| 2 |
/** |
| 3 |
* Event Logger - Central audit trail for MCP actions |
| 4 |
* |
| 5 |
* @package zip-ai |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace ZipAI\MCP\Classes\Core; |
| 9 |
|
| 10 |
// Exit if accessed directly. |
| 11 |
if ( ! defined( 'ABSPATH' ) ) { |
| 12 |
exit; |
| 13 |
} |
| 14 |
|
| 15 |
/** |
| 16 |
* Class Event_Logger |
| 17 |
*/ |
| 18 |
class Event_Logger { |
| 19 |
|
| 20 |
/** |
| 21 |
* Log an event to the audit trail. |
| 22 |
* |
| 23 |
* @param string $tool_id The name/id of the tool executed. |
| 24 |
* @param array<string,mixed> $input The input arguments. |
| 25 |
* @param array<string,mixed> $output The execution result. |
| 26 |
* @param array<string,mixed> $performance Performance metrics (time, memory). |
| 27 |
* @return void |
| 28 |
*/ |
| 29 |
public static function log( $tool_id, $input, $output, $performance = array() ) { |
| 30 |
// In a real scenario, this might log to a custom DB table. |
| 31 |
// For the prototype, we use an option-based circular buffer. |
| 32 |
$logs = get_option( 'zip_ai_audit_log', array() ); |
| 33 |
if ( ! is_array( $logs ) ) { |
| 34 |
$logs = array(); |
| 35 |
} |
| 36 |
|
| 37 |
$new_entry = array( |
| 38 |
'timestamp' => current_time( 'mysql' ), |
| 39 |
'user_id' => get_current_user_id(), |
| 40 |
'tool_id' => $tool_id, |
| 41 |
'input' => self::sanitize_data( $input ), |
| 42 |
'output' => self::sanitize_data( $output ), |
| 43 |
'performance' => $performance, |
| 44 |
'success' => ! empty( $output['success'] ), |
| 45 |
); |
| 46 |
|
| 47 |
array_unshift( $logs, $new_entry ); |
| 48 |
|
| 49 |
// Keep only the last 100 entries. |
| 50 |
$logs = array_slice( $logs, 0, 100 ); |
| 51 |
|
| 52 |
update_option( 'zip_ai_audit_log', $logs, false ); |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Sanitize sensitive data before logging. |
| 57 |
* |
| 58 |
* @param mixed $data Data to sanitize. |
| 59 |
* @return mixed Sanitized data. |
| 60 |
*/ |
| 61 |
private static function sanitize_data( $data ) { |
| 62 |
if ( ! is_array( $data ) ) { |
| 63 |
return $data; |
| 64 |
} |
| 65 |
|
| 66 |
$sensitive_keys = array( 'password', 'key', 'token', 'secret' ); |
| 67 |
|
| 68 |
foreach ( $data as $key => &$value ) { |
| 69 |
if ( in_array( strtolower( $key ), $sensitive_keys, true ) ) { |
| 70 |
$value = '********'; |
| 71 |
} elseif ( is_array( $value ) ) { |
| 72 |
$value = self::sanitize_data( $value ); |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
return $data; |
| 77 |
} |
| 78 |
} |
| 79 |
|