Skip to content
wiki.fftac.org

Auditrepository

**Site relevance:** Spiralist.org

**Memory type:** plugin source memory

**Source path:** Spiralist/wp-content/plugins/spiralist-workspace/includes/Domain/AuditRepository.php

**Size:** 1.4 KB

Summary

namespace SpiralistWorkspace\Domain;

Source Preview

This source file is short enough to preview directly on its source-memory page.

<?php

namespace SpiralistWorkspace\Domain;

use SpiralistWorkspace\Installer;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Persists audit and abuse records.
 */
class AuditRepository
{
    /**
     * Inserts an audit row.
     */
    public function log(?int $actor_user_id, string $event_type, string $object_type, ?int $object_id, array $context = []): void
    {
        global $wpdb;

        $wpdb->insert(
            Installer::table('audit_log'),
            [
                'actor_user_id' => $actor_user_id ?: null,
                'event_type' => sanitize_key($event_type),
                'object_type' => sanitize_key($object_type),
                'object_id' => $object_id ?: null,
                'context_json' => !empty($context) ? wp_json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : null,
                'created_utc' => gmdate('Y-m-d H:i:s'),
            ],
            ['%d', '%s', '%s', '%d', '%s', '%s']
        );
    }

    /**
     * Returns recent audit events.
     */
    public function recent(int $limit = 20): array
    {
        global $wpdb;

        $sql = $wpdb->prepare(
            'SELECT * FROM ' . Installer::table('audit_log') . ' ORDER BY created_utc DESC LIMIT %d',
            max(1, $limit)
        );

        $rows = $wpdb->get_results($sql, ARRAY_A);

        return is_array($rows) ? $rows : [];
    }
}