Class Uai1 Usage Log
**Site relevance:** Spiralist.org
**Memory type:** plugin source memory
**Source path:** Spiralist/wp-content/plugins/uai-1-wordpress/includes/class-uai1-usage-log.php
**Size:** 2.9 KB
Summary
if (!defined('ABSPATH'))
Source Preview
This source file is short enough to preview directly on its source-memory page.
<?php
if (!defined('ABSPATH')) {
exit;
}
class UAI1_Usage_Log
{
public static function install(): void
{
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$table = self::table_name();
$charset = $wpdb->get_charset_collate();
$sql = "CREATE TABLE {$table} (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
participant_id VARCHAR(64) NULL DEFAULT NULL,
request_method VARCHAR(10) NOT NULL,
route VARCHAR(191) NOT NULL,
status_code SMALLINT UNSIGNED NOT NULL,
ip_address VARCHAR(64) NOT NULL DEFAULT '',
user_agent VARCHAR(255) NOT NULL DEFAULT '',
details LONGTEXT NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY participant_id (participant_id),
KEY route (route),
KEY created_at (created_at)
) {$charset};";
dbDelta($sql);
}
public static function log_rest_request(WP_REST_Request $request, ?string $participant_id = null, int $status_code = 200, array $details = []): void
{
global $wpdb;
$method = strtoupper((string) $request->get_method());
$route = substr((string) $request->get_route(), 0, 191);
$ip_address = substr(self::request_ip(), 0, 64);
$user_agent = substr((string) ($request->get_header('user-agent') ?: ($_SERVER['HTTP_USER_AGENT'] ?? '')), 0, 255);
$encoded_details = !empty($details)
? wp_json_encode($details, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
: null;
$wpdb->insert(
self::table_name(),
[
'participant_id' => $participant_id !== null && $participant_id !== '' ? $participant_id : null,
'request_method' => $method,
'route' => $route,
'status_code' => max(100, min(599, $status_code)),
'ip_address' => $ip_address,
'user_agent' => $user_agent,
'details' => $encoded_details,
'created_at' => gmdate('Y-m-d H:i:s'),
],
['%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s']
);
}
private static function table_name(): string
{
global $wpdb;
return $wpdb->prefix . 'uai1_usage_log';
}
private static function request_ip(): string
{
$forwarded = (string) ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? '');
if ($forwarded !== '') {
$parts = array_map('trim', explode(',', $forwarded));
if (!empty($parts[0])) {
return $parts[0];
}
}
$remote_addr = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
return $remote_addr !== '' ? $remote_addr : 'unknown';
}
}