settings = Plugin::get_settings( 'users' );
add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] );
add_action( 'adminease_after_field_render', [ $this, 'adminease_after_field_render' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
add_action( 'wp_ajax_adminease_get_audit_log', [ $this, 'ajax_get_audit_log' ] );
add_action( 'wp_ajax_adminease_clear_audit_log', [ $this, 'ajax_clear_audit_log' ] );
add_action( self::CLEANUP_HOOK, [ $this, 'cleanup_old_logs' ] );
add_action( 'adminease_audit_log', [ $this, 'adminease_audit_log' ], 10, 5 );
add_action( 'add_option_adminease_settings', [ $this, 'add_option_adminease_settings' ], 10, 2 );
add_action( 'update_option_adminease_settings', [ $this, 'update_option_adminease_settings' ], 10, 2 );
add_action( 'user_register', [ $this, 'user_register' ] );
add_action( 'set_user_role', [ $this, 'set_user_role' ], 10, 3 );
if( is_multisite() ) {
add_action( 'add_user_to_blog', [ $this, 'add_user_to_blog' ], 10, 3 );
add_action( 'remove_user_from_blog', [ $this, 'remove_user_from_blog' ], 10, 2 );
add_action( 'wpmu_delete_user', [ $this, 'delete_user' ] );
} else {
add_action( 'delete_user', [ $this, 'delete_user' ] );
}
add_action( 'activated_plugin', [ $this, 'activated_plugin' ], 10, 2 );
add_action( 'deactivated_plugin', [ $this, 'deactivated_plugin' ], 10, 2 );
add_action( 'delete_plugin', [ $this, 'delete_plugin' ] );
add_action( 'deleted_plugin', [ $this, 'deleted_plugin' ], 10, 2 );
add_action( 'switch_theme', [ $this, 'switch_theme' ] );
add_action( 'wp_trash_post', [ $this, 'wp_trash_post' ] );
add_action( 'untrashed_post', [ $this, 'untrashed_post' ] );
add_action( 'transition_post_status', [ $this, 'transition_post_status' ], 10, 3 );
add_action( 'before_delete_post', [ $this, 'before_delete_post' ] );
add_action( 'delete_attachment', [ $this, 'before_delete_post' ] );
if( !empty( $this->settings['audit_log_enabled'] ) ) {
if( '1' !== get_option( self::TABLE_OPTION ) ) {
$this->create_table();
}
if( !wp_next_scheduled( self::CLEANUP_HOOK ) ) {
wp_schedule_event( time(), 'daily', self::CLEANUP_HOOK );
}
}
}
/**
* The instance the plugin registered, for add-ons that read the log.
*
* @return AuditLog|null
*/
public static function get_instance(): ?AuditLog {
return self::$instance;
}
/**
* Adds the Audit Log fields to the Users tab.
*
* @param array $fields Associative array of existing settings fields.
*
* @return array Modified settings fields array.
*/
public function adminease_settings_fields( array $fields ): array {
$fields['users']['fields'][] = [
'type' => 'switch',
'id' => 'audit-log-enabled',
'name' => 'adminease[users][audit_log_enabled]',
'value' => $this->settings['audit_log_enabled'] ?? '',
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input toggle-field',
'label' => __( 'Audit Log', 'adminease' ),
'description' => __( 'Keeps a record of who changed what in the admin: AdminEase settings, users and their roles, plugins, themes, and posts moved to the trash or deleted. Useful when more than one person looks after the site. Setting values and passwords are never stored, only what was changed.', 'adminease' ),
'child_fields' => [
[
'type' => 'switch',
'id' => 'audit-log-auto-load',
'name' => 'adminease[users][audit_log_auto_load]',
'value' => $this->settings['audit_log_auto_load'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Auto-Load Audit Log', 'adminease' ),
'field_description' => __( 'Load the log automatically when this section is opened.', 'adminease' ),
'attributes' => [
'data-parent' => 'audit-log-enabled',
],
],
[
'type' => 'number',
'id' => 'audit-log-max-entries',
'name' => 'adminease[users][audit_log_max_entries]',
'value' => $this->settings['audit_log_max_entries'] ?? '10000',
'label_class' => '',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Maximum Log Entries', 'adminease' ),
'description' => __( 'Maximum number of entries to keep in the log (100-100000). The oldest are removed first.', 'adminease' ),
'attributes' => [
'data-parent' => 'audit-log-enabled',
'min' => '100',
'max' => '100000',
],
],
[
'type' => 'select',
'id' => 'audit-log-auto-clear',
'name' => 'adminease[users][audit_log_auto_clear]',
'value' => $this->settings['audit_log_auto_clear'] ?? '90_days',
'label_class' => '',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Auto Clear Logs After', 'adminease' ),
'description' => __( 'Automatically delete entries older than this period.', 'adminease' ),
'options' => [
'30_days' => __( '30 Days', 'adminease' ),
'90_days' => __( '90 Days', 'adminease' ),
'180_days' => __( '180 Days', 'adminease' ),
'1_year' => __( '1 Year', 'adminease' ),
'never' => __( 'Never', 'adminease' ),
],
'attributes' => [
'data-parent' => 'audit-log-enabled',
],
],
],
];
return $fields;
}
/**
* Enqueues the log viewer on the AdminEase page.
*
* @param string $hook The current admin page hook suffix.
*
* @return void
*/
public function admin_enqueue_scripts( string $hook ): void {
if( 'toplevel_page_adminease' !== $hook ) {
return;
}
wp_enqueue_style(
ADMINEASE_NAME . 'AuditLog',
ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseAuditLog.css',
[ ADMINEASE_NAME ],
filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseAuditLog.css' )
);
wp_enqueue_script(
ADMINEASE_NAME . 'AuditLog',
ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseAuditLog.js',
[ 'jquery', ADMINEASE_NAME ],
filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseAuditLog.js' ),
true
);
wp_localize_script(
ADMINEASE_NAME . 'AuditLog',
ADMINEASE_NAME . 'AuditLogAjaxObj',
[
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'security' => [
'getAuditLog' => wp_create_nonce( 'adminease_get_audit_log' ),
'clearAuditLog' => wp_create_nonce( 'adminease_clear_audit_log' ),
],
'autoLoad' => !empty( $this->settings['audit_log_auto_load'] ),
'i18n' => [
'confirmClear' => esc_html__( 'Are you sure you want to clear the whole audit log? A note that you cleared it stays in the log.', 'adminease' ),
'logCleared' => esc_html__( 'Audit log cleared.', 'adminease' ),
'loadFailed' => esc_html__( 'Failed to load the audit log.', 'adminease' ),
'clearFailed' => esc_html__( 'Failed to clear the audit log.', 'adminease' ),
'networkError' => esc_html__( 'Network error', 'adminease' ),
/* translators: 1: current page, 2: total pages */
'paginationInfo' => esc_html__( 'Page %1$s of %2$s', 'adminease' ),
/* translators: 1: start number, 2: end number, 3: total count */
'entryCount' => esc_html__( 'Showing %1$s-%2$s of %3$s entries', 'adminease' ),
'btnProcessing' => esc_html__( 'Processing…', 'adminease' ),
'btnComplete' => esc_html__( 'Complete!', 'adminease' ),
],
]
);
}
/**
* Renders the log viewer underneath the feature switch.
*
* @param array $field The field information.
*
* @return void
*/
public function adminease_after_field_render( array $field ): void {
if( 'audit-log-enabled' !== $field['id'] ) {
return;
}
?>
'ae-icon' ] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Trusted SVG markup. ?>
log( sanitize_key( (string) $event ), sanitize_key( (string) $action ), (int) $object_id, (string) $object_name, (array) $details );
}
/**
* Logs the first time AdminEase settings are stored on a site.
*
* @param string $option The option name.
* @param mixed $value The stored value.
*
* @return void
*/
public function add_option_adminease_settings( string $option, $value ): void {
$this->update_option_adminease_settings( [], $value );
}
/**
* Logs which AdminEase settings changed. Only the keys are kept, never the values.
*
* @param mixed $old_value The previous settings.
* @param mixed $value The new settings.
*
* @return void
*/
public function update_option_adminease_settings( $old_value, $value ): void {
$old_value = is_array( $old_value ) ? $old_value : [];
$value = is_array( $value ) ? $value : [];
if( !empty( $value['users']['audit_log_enabled'] ) && empty( $old_value['users']['audit_log_enabled'] ) ) {
$this->create_table();
}
if( empty( $value['users']['audit_log_enabled'] ) && empty( $old_value['users']['audit_log_enabled'] ) ) {
return;
}
$changed = [];
foreach( array_unique( array_merge( array_keys( $old_value ), array_keys( $value ) ) ) as $tab ) {
$old_tab = is_array( $old_value[ $tab ] ?? null ) ? $old_value[ $tab ] : [];
$new_tab = is_array( $value[ $tab ] ?? null ) ? $value[ $tab ] : [];
$keys = [];
foreach( array_unique( array_merge( array_keys( $old_tab ), array_keys( $new_tab ) ) ) as $key ) {
$old = $old_tab[ $key ] ?? null;
$new = $new_tab[ $key ] ?? null;
if( $this->is_blank( $old ) && $this->is_blank( $new ) ) {
continue;
}
if( $old != $new ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual -- Saved values switch between strings and numbers.
$keys[] = (string) $key;
}
}
if( !empty( $keys ) ) {
$changed[ (string) $tab ] = $keys;
}
}
if( empty( $changed ) ) {
return;
}
$this->log( 'settings', 'settings_changed', 0, '', $changed, true );
}
/**
* Whether a saved setting holds nothing: missing, empty or a switch that is off.
*
* @param mixed $value The saved value.
*
* @return bool
*/
private function is_blank( $value ): bool {
return null === $value || false === $value || '' === $value || '0' === $value || 0 === $value || [] === $value;
}
/**
* Logs a new user.
*
* @param int $user_id The new user's ID.
*
* @return void
*/
public function user_register( $user_id ): void {
$user = get_userdata( (int) $user_id );
if( !$user ) {
return;
}
$this->log( 'users', 'user_created', $user->ID, $user->user_login, [ 'roles' => array_values( $user->roles ) ] );
}
/**
* Logs a role change. A role given while a user is created is part of that event instead.
*
* @param int $user_id The user's ID.
* @param string $role The new role.
* @param array $old_roles The roles the user had before.
*
* @return void
*/
public function set_user_role( $user_id, $role, $old_roles ): void {
$old_roles = array_values( (array) $old_roles );
if( empty( $old_roles ) || [ $role ] === $old_roles ) {
return;
}
$user = get_userdata( (int) $user_id );
if( !$user ) {
return;
}
$this->log( 'users', 'user_role_changed', $user->ID, $user->user_login, [ 'from' => $old_roles, 'to' => (string) $role ] );
}
/**
* Logs a user being added to this site of a network.
*
* @param int $user_id The user's ID.
* @param string $role The role given on this site.
* @param int $blog_id The site the user was added to.
*
* @return void
*/
public function add_user_to_blog( $user_id, $role, $blog_id ): void {
if( get_current_blog_id() !== (int) $blog_id ) {
return;
}
$user = get_userdata( (int) $user_id );
if( !$user ) {
return;
}
$this->log( 'users', 'user_added', $user->ID, $user->user_login, [ 'roles' => [ (string) $role ] ] );
}
/**
* Logs a user being removed from this site of a network.
*
* @param int $user_id The user's ID.
* @param int $blog_id The site the user was removed from.
*
* @return void
*/
public function remove_user_from_blog( $user_id, $blog_id ): void {
if( get_current_blog_id() !== (int) $blog_id ) {
return;
}
$user = get_userdata( (int) $user_id );
if( !$user ) {
return;
}
$this->log( 'users', 'user_removed', $user->ID, $user->user_login );
}
/**
* Logs a deleted user. Runs before the account is gone, so the name can still be read.
*
* @param int $user_id The user's ID.
*
* @return void
*/
public function delete_user( $user_id ): void {
$user = get_userdata( (int) $user_id );
if( !$user ) {
return;
}
$this->log( 'users', 'user_deleted', $user->ID, $user->user_login );
}
/**
* Logs a plugin being activated.
*
* @param string $plugin Plugin file relative to the plugins folder.
* @param bool $network_wide Whether it was activated for the whole network.
*
* @return void
*/
public function activated_plugin( $plugin, $network_wide = false ): void {
$this->log( 'plugins', $network_wide ? 'plugin_network_activated' : 'plugin_activated', 0, $this->get_plugin_name( (string) $plugin ), [ 'file' => (string) $plugin ] );
}
/**
* Logs a plugin being deactivated.
*
* @param string $plugin Plugin file relative to the plugins folder.
* @param bool $network_wide Whether it was deactivated for the whole network.
*
* @return void
*/
public function deactivated_plugin( $plugin, $network_wide = false ): void {
$this->log( 'plugins', $network_wide ? 'plugin_network_deactivated' : 'plugin_deactivated', 0, $this->get_plugin_name( (string) $plugin ), [ 'file' => (string) $plugin ] );
}
/**
* Reads a plugin's name before its files are deleted.
*
* @param string $plugin Plugin file relative to the plugins folder.
*
* @return void
*/
public function delete_plugin( $plugin ): void {
$this->deleting_plugins[ (string) $plugin ] = $this->get_plugin_name( (string) $plugin );
}
/**
* Logs a plugin that was deleted.
*
* @param string $plugin Plugin file relative to the plugins folder.
* @param bool $deleted Whether the files were removed.
*
* @return void
*/
public function deleted_plugin( $plugin, $deleted ): void {
if( !$deleted ) {
return;
}
$name = $this->deleting_plugins[ (string) $plugin ] ?? (string) $plugin;
$this->log( 'plugins', 'plugin_deleted', 0, $name, [ 'file' => (string) $plugin ] );
}
/**
* Logs a theme switch.
*
* @param string $new_name The new theme's name.
*
* @return void
*/
public function switch_theme( $new_name ): void {
$this->log( 'themes', 'theme_switched', 0, (string) $new_name );
}
/**
* Logs a post moved to the trash.
*
* @param int $post_id The post ID.
*
* @return void
*/
public function wp_trash_post( $post_id ): void {
$this->log_post( (int) $post_id, 'post_trashed' );
}
/**
* Logs a post restored from the trash.
*
* @param int $post_id The post ID.
*
* @return void
*/
public function untrashed_post( $post_id ): void {
$this->log_post( (int) $post_id, 'post_restored' );
}
/**
* Logs a post moving between statuses, such as published to draft. Creating a post and
* the trash have their own entries, so those moves are left out here.
*
* @param string $new_status The new status.
* @param string $old_status The previous status.
* @param \WP_Post $post The post.
*
* @return void
*/
public function transition_post_status( $new_status, $old_status, $post ): void {
$skip = [ 'new', 'auto-draft', 'inherit', 'trash' ];
if( $new_status === $old_status || in_array( $new_status, $skip, true ) || in_array( $old_status, $skip, true ) || !$post instanceof \WP_Post ) {
return;
}
if( 0 === strpos( (string) $new_status, 'wc-' ) || 0 === strpos( (string) $old_status, 'wc-' ) ) {
return;
}
$this->log_post( $post->ID, 'post_status_changed', [ 'from' => (string) $old_status, 'to' => (string) $new_status ] );
}
/**
* Logs a post or attachment deleted for good.
*
* @param int $post_id The post ID.
*
* @return void
*/
public function before_delete_post( $post_id ): void {
$this->log_post( (int) $post_id, 'post_deleted' );
}
/**
* Logs a post event, leaving out revisions, auto drafts and types with no admin screen.
*
* @param int $post_id The post ID.
* @param string $action The action slug.
* @param array $details Extra data.
*
* @return void
*/
private function log_post( int $post_id, string $action, array $details = [] ): void {
$post = get_post( $post_id );
if( !$post || 'auto-draft' === $post->post_status ) {
return;
}
$post_type = get_post_type_object( $post->post_type );
if( !$post_type || empty( $post_type->show_ui ) || 'revision' === $post->post_type ) {
return;
}
$this->log( 'posts', $action, $post->ID, $post->post_title, array_merge( [ 'post_type' => $post->post_type ], $details ) );
}
/**
* Reads a plugin's display name, falling back to its file.
*
* @param string $plugin Plugin file relative to the plugins folder.
*
* @return string The plugin name.
*/
private function get_plugin_name( string $plugin ): string {
if( !function_exists( 'get_plugin_data' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$file = WP_PLUGIN_DIR . '/' . $plugin;
if( !file_exists( $file ) ) {
return $plugin;
}
$data = get_plugin_data( $file, false, false );
return !empty( $data['Name'] ) ? $data['Name'] : $plugin;
}
/**
* Whether the log is on for the site currently loaded, which can change during a push.
*
* @return bool
*/
public function is_enabled(): bool {
$settings = get_option( 'adminease_settings', [] );
return is_array( $settings ) && !empty( $settings['users']['audit_log_enabled'] );
}
/**
* The log table of the site currently loaded.
*
* @return string
*/
private function get_table_name(): string {
global $wpdb;
return $wpdb->prefix . self::TABLE;
}
/**
* Writes one entry.
*
* @param string $event Event group, one of the keys of get_event_labels().
* @param string $action Action slug.
* @param int $object_id ID of the user or post involved, or 0.
* @param string $object_name Name of what was changed.
* @param array $details Extra data, stored as JSON.
* @param bool $force Write even when the log is switched off.
*
* @return void
*/
public function log( string $event, string $action, int $object_id = 0, string $object_name = '', array $details = [], bool $force = false ): void {
if( !$force && !$this->is_enabled() ) {
return;
}
global $wpdb;
$user = wp_get_current_user();
if( class_exists( UserSwitch::class ) && !in_array( $action, [ 'user_switched', 'user_switched_back' ], true ) ) {
$original = UserSwitch::get_original_user_id();
if( $original && ( $original_user = get_userdata( $original ) ) ) {
$details['switched_from'] = $original_user->user_login;
}
}
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Real-time logging requires direct insert
$wpdb->insert(
$this->get_table_name(),
[
'timestamp' => current_time( 'mysql' ),
'user_id' => $user->ID,
'user_login' => $user->ID ? $user->user_login : '',
'user_ip' => $user->ID ? Utils::get_client_ip() : '',
'event' => mb_substr( $event, 0, 20 ),
'action' => mb_substr( $action, 0, 40 ),
'object_id' => $object_id,
'object_name' => mb_substr( $object_name, 0, 255 ),
'details' => !empty( $details ) ? wp_json_encode( $details ) : '',
],
[ '%s', '%d', '%s', '%s', '%s', '%s', '%d', '%s', '%s' ]
);
}
/**
* The event groups, for the filter and the badges.
*
* @return array Event slug => label.
*/
public function get_event_labels(): array {
$labels = [
'settings' => __( 'Settings', 'adminease' ),
'users' => __( 'Users', 'adminease' ),
'plugins' => __( 'Plugins', 'adminease' ),
'themes' => __( 'Themes', 'adminease' ),
'posts' => __( 'Posts', 'adminease' ),
];
/**
* Filters the event groups of the audit log. Slugs are at most 20 characters.
*
* @param array $labels Event slug => translated label.
*/
$labels = (array) apply_filters( 'adminease_audit_log_event_labels', $labels );
$labels['log'] = __( 'Audit Log', 'adminease' );
return $labels;
}
/**
* Builds the sentence shown for an entry, in the reader's language.
*
* @param array $entry A log row.
*
* @return string The description.
*/
public function describe( array $entry ): string {
$name = (string) ( $entry['object_name'] ?? '' );
$details = json_decode( (string) ( $entry['details'] ?? '' ), true );
$details = is_array( $details ) ? $details : [];
switch( $entry['action'] ?? '' ) {
case 'settings_changed':
$parts = [];
foreach( $details as $tab => $keys ) {
$parts[] = $this->get_tab_title( (string) $tab ) . ': ' . implode( ', ', array_map( function( $key ) use ( $tab ) {
return $this->get_field_label( (string) $tab, (string) $key );
}, (array) $keys ) );
}
/* translators: %s: list of the settings that changed, grouped by tab */
$description = sprintf( __( 'Changed AdminEase settings. %s', 'adminease' ), implode( '; ', $parts ) );
break;
case 'user_created':
/* translators: 1: user name, 2: role */
$description = sprintf( __( 'Created user %1$s (%2$s)', 'adminease' ), $name, $this->get_role_names( (array) ( $details['roles'] ?? [] ) ) );
break;
case 'user_added':
/* translators: 1: user name, 2: role */
$description = sprintf( __( 'Added user %1$s to this site (%2$s)', 'adminease' ), $name, $this->get_role_names( (array) ( $details['roles'] ?? [] ) ) );
break;
case 'user_role_changed':
/* translators: 1: user name, 2: old role, 3: new role */
$description = sprintf( __( 'Changed the role of %1$s from %2$s to %3$s', 'adminease' ), $name, $this->get_role_names( (array) ( $details['from'] ?? [] ) ), $this->get_role_names( [ (string) ( $details['to'] ?? '' ) ] ) );
break;
case 'user_removed':
/* translators: %s: user name */
$description = sprintf( __( 'Removed user %s from this site', 'adminease' ), $name );
break;
case 'user_deleted':
/* translators: %s: user name */
$description = sprintf( __( 'Deleted user %s', 'adminease' ), $name );
break;
case 'user_switched':
/* translators: %s: user name */
$description = sprintf( __( 'Switched to user %s', 'adminease' ), $name );
break;
case 'user_switched_back':
/* translators: %s: user name */
$description = sprintf( __( 'Switched back to user %s', 'adminease' ), $name );
break;
case 'plugin_activated':
/* translators: %s: plugin name */
$description = sprintf( __( 'Activated plugin %s', 'adminease' ), $name );
break;
case 'plugin_network_activated':
/* translators: %s: plugin name */
$description = sprintf( __( 'Activated plugin %s for the whole network', 'adminease' ), $name );
break;
case 'plugin_deactivated':
/* translators: %s: plugin name */
$description = sprintf( __( 'Deactivated plugin %s', 'adminease' ), $name );
break;
case 'plugin_network_deactivated':
/* translators: %s: plugin name */
$description = sprintf( __( 'Deactivated plugin %s for the whole network', 'adminease' ), $name );
break;
case 'plugin_deleted':
/* translators: %s: plugin name */
$description = sprintf( __( 'Deleted plugin %s', 'adminease' ), $name );
break;
case 'theme_switched':
/* translators: %s: theme name */
$description = sprintf( __( 'Switched the theme to %s', 'adminease' ), $name );
break;
case 'post_trashed':
/* translators: 1: post type name, 2: post title */
$description = sprintf( __( 'Moved %1$s "%2$s" to the trash', 'adminease' ), $this->get_post_type_name( $details ), $name );
break;
case 'post_restored':
/* translators: 1: post type name, 2: post title */
$description = sprintf( __( 'Restored %1$s "%2$s" from the trash', 'adminease' ), $this->get_post_type_name( $details ), $name );
break;
case 'post_status_changed':
/* translators: 1: post type name, 2: post title, 3: old status, 4: new status */
$description = sprintf( __( 'Changed the status of %1$s "%2$s" from %3$s to %4$s', 'adminease' ), $this->get_post_type_name( $details ), $name, $this->get_post_status_name( (string) ( $details['from'] ?? '' ) ), $this->get_post_status_name( (string) ( $details['to'] ?? '' ) ) );
break;
case 'post_deleted':
/* translators: 1: post type name, 2: post title */
$description = sprintf( __( 'Permanently deleted %1$s "%2$s"', 'adminease' ), $this->get_post_type_name( $details ), $name );
break;
case 'log_cleared':
$description = __( 'Cleared the audit log', 'adminease' );
break;
default:
$description = '' !== $name ? $name : (string) ( $entry['action'] ?? '' );
}
/**
* Filters the sentence shown for an audit log entry. Add-ons describe their own actions here.
*
* @param string $description The sentence.
* @param array $entry The log row.
* @param array $details The decoded details.
*/
return (string) apply_filters( 'adminease_audit_log_description', $description, $entry, $details );
}
/**
* Reads the title of a settings tab.
*
* @param string $tab The tab key.
*
* @return string The title, or the key when the tab is gone.
*/
private function get_tab_title( string $tab ): string {
if( null === $this->tab_titles ) {
$this->tab_titles = wp_list_pluck( Plugin::get_plugin_fields(), 'title' );
}
return (string) ( $this->tab_titles[ $tab ] ?? $tab );
}
/**
* Reads the label of a setting, so the log names it the way the settings screen does.
*
* @param string $tab The tab key.
* @param string $key The setting key.
*
* @return string The label, or the key with spaces when the field is gone.
*/
private function get_field_label( string $tab, string $key ): string {
if( null === $this->field_labels ) {
$this->field_labels = [];
foreach( Plugin::get_plugin_fields() as $group ) {
$this->collect_field_labels( (array) ( $group['fields'] ?? [] ) );
}
}
return $this->field_labels[ $tab ][ $key ] ?? str_replace( '_', ' ', $key );
}
/**
* Adds the labels of a list of fields and their child fields to the lookup.
*
* @param array $fields Settings fields.
*
* @return void
*/
private function collect_field_labels( array $fields ): void {
foreach( $fields as $field ) {
if( !is_array( $field ) ) {
continue;
}
if( !empty( $field['label'] ) && preg_match( '/^adminease\[([^\]]+)\]\[([^\]]+)\]/', (string) ( $field['name'] ?? '' ), $matches ) ) {
$this->field_labels[ $matches[1] ][ $matches[2] ] = trim( wp_strip_all_tags( (string) $field['label'] ) );
}
if( !empty( $field['child_fields'] ) ) {
$this->collect_field_labels( (array) $field['child_fields'] );
}
}
}
/**
* Turns role slugs into their translated names.
*
* @param array $roles Role slugs.
*
* @return string Comma separated names, or "no role".
*/
private function get_role_names( array $roles ): string {
$names = [];
foreach( array_filter( $roles ) as $role ) {
$names[] = isset( wp_roles()->roles[ $role ] ) ? translate_user_role( wp_roles()->roles[ $role ]['name'] ) : $role;
}
return !empty( $names ) ? implode( ', ', $names ) : __( 'no role', 'adminease' );
}
/**
* Reads the post type name stored with a post event.
*
* @param array $details The entry details.
*
* @return string The singular name, in lower case.
*/
private function get_post_type_name( array $details ): string {
$post_type = (string) ( $details['post_type'] ?? '' );
$object = get_post_type_object( $post_type );
return $object ? mb_strtolower( $object->labels->singular_name ) : $post_type;
}
/**
* Reads the translated name of a post status.
*
* @param string $status The status slug.
*
* @return string The name, or the slug when the status is gone.
*/
private function get_post_status_name( string $status ): string {
$object = get_post_status_object( $status );
return $object ? (string) $object->label : $status;
}
/**
* Formats a stored timestamp, which is written in the site's time zone.
*
* @param string $timestamp MySQL datetime as stored.
*
* @return string Localised date and time.
*/
public function format_timestamp( string $timestamp ): string {
try {
$datetime = new \DateTimeImmutable( $timestamp, wp_timezone() );
} catch( \Exception $e ) {
return $timestamp;
}
return (string) wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $datetime->getTimestamp() );
}
/**
* Builds the WHERE clause for the filters.
*
* @param array $args Filters: event and search.
* @param array $where_values Receives the placeholder values.
*
* @return string The WHERE clause, or an empty string.
*/
private function build_where( array $args, array &$where_values ): string {
global $wpdb;
$where = [];
$where_values = [];
if( !empty( $args['event'] ) && isset( $this->get_event_labels()[ $args['event'] ] ) ) {
$where[] = 'event = %s';
$where_values[] = $args['event'];
}
if( !empty( $args['search'] ) ) {
$like = '%' . $wpdb->esc_like( $args['search'] ) . '%';
$where[] = '(user_login LIKE %s OR object_name LIKE %s OR user_ip LIKE %s OR details LIKE %s)';
$where_values[] = $like;
$where_values[] = $like;
$where_values[] = $like;
$where_values[] = $like;
}
return !empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : '';
}
/**
* Retrieves a page of entries, newest first.
*
* @param array $args Filters plus page and per_page.
*
* @return array Log rows.
*/
public function get_entries( array $args = [] ): array {
global $wpdb;
$per_page = max( 1, min( 500, (int) ( $args['per_page'] ?? 50 ) ) );
$offset = ( max( 1, (int) ( $args['page'] ?? 1 ) ) - 1 ) * $per_page;
$where_values = [];
$where_clause = $this->build_where( $args, $where_values );
$table = $this->get_table_name();
$where_values[] = $per_page;
$where_values[] = $offset;
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name comes from $wpdb->prefix; every filter value is placeheld.
$query = $wpdb->prepare( "SELECT * FROM {$table} {$where_clause} ORDER BY id DESC LIMIT %d OFFSET %d", $where_values );
// phpcs:enable
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
$results = $wpdb->get_results( $query, ARRAY_A );
return is_array( $results ) ? $results : [];
}
/**
* Counts the entries matching the filters.
*
* @param array $args Filters.
*
* @return int The count.
*/
public function get_total_count( array $args = [] ): int {
global $wpdb;
$where_values = [];
$where_clause = $this->build_where( $args, $where_values );
$table = $this->get_table_name();
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name comes from $wpdb->prefix; every filter value is placeheld.
$query = "SELECT COUNT(*) FROM {$table} {$where_clause}";
if( !empty( $where_values ) ) {
$query = $wpdb->prepare( $query, $where_values ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
}
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
return (int) $wpdb->get_var( $query );
}
/**
* Whether this site's log table exists.
*
* @return bool
*/
public function table_exists(): bool {
global $wpdb;
$table = $this->get_table_name();
$suppress = $wpdb->suppress_errors();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name comes from $wpdb->prefix.
$exists = false !== $wpdb->query( "SELECT 1 FROM {$table} LIMIT 1" );
$wpdb->suppress_errors( $suppress );
return $exists;
}
/**
* Checks the nonce and capability of a log request, and ends it when either fails.
*
* @param string $action The nonce action.
*
* @return void
*/
private function verify_request( string $action ): void {
if( !isset( $_REQUEST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_REQUEST['security'] ) ), $action ) ) {
wp_send_json_error( new WP_Error( 'security_error', __( 'Security check failed. Refresh the page and try again.', 'adminease' ) ), 403 );
}
if( !current_user_can( 'manage_options' ) ) {
wp_send_json_error( new WP_Error( 'insufficient_permissions', __( 'Insufficient permissions.', 'adminease' ) ), 403 );
}
if( !$this->is_enabled() || !$this->table_exists() ) {
wp_send_json_error( new WP_Error( 'disabled', __( 'Switch the audit log on and save first.', 'adminease' ) ) );
}
}
/**
* Reads the filters sent with a request. The caller has verified the nonce.
*
* @return array Sanitised filters.
*/
public function get_request_filters(): array {
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Verified by the calling handler.
return [
'event' => isset( $_REQUEST['event'] ) ? sanitize_key( wp_unslash( $_REQUEST['event'] ) ) : '',
'search' => isset( $_REQUEST['search'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['search'] ) ) : '',
'page' => isset( $_REQUEST['page'] ) ? absint( $_REQUEST['page'] ) : 1,
'per_page' => isset( $_REQUEST['per_page'] ) ? absint( $_REQUEST['per_page'] ) : 50,
];
// phpcs:enable WordPress.Security.NonceVerification.Recommended
}
/**
* AJAX handler that returns a rendered page of the log.
*
* @return void
*/
public function ajax_get_audit_log(): void {
$this->verify_request( 'adminease_get_audit_log' );
$args = $this->get_request_filters();
wp_send_json_success(
[
'table_html' => $this->render_rows( $this->get_entries( $args ) ),
'total' => $this->get_total_count( $args ),
'page' => max( 1, $args['page'] ),
'per_page' => max( 1, $args['per_page'] ),
]
);
}
/**
* AJAX handler that empties the log and records who did it.
*
* @return void
*/
public function ajax_clear_audit_log(): void {
$this->verify_request( 'adminease_clear_audit_log' );
global $wpdb;
$table = $this->get_table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Intentional log clearing
if( false === $wpdb->query( "TRUNCATE TABLE {$table}" ) ) {
wp_send_json_error( new WP_Error( 'clear_failed', __( 'Failed to clear the audit log.', 'adminease' ) ) );
}
$this->log( 'log', 'log_cleared' );
wp_send_json_success( __( 'Audit log cleared.', 'adminease' ) );
}
/**
* The name shown for the person behind an entry.
*
* @param array $entry A log row.
*
* @return string The user name, or "System" for changes made without one.
*/
public function get_user_label( array $entry ): string {
return '' !== (string) ( $entry['user_login'] ?? '' ) ? (string) $entry['user_login'] : __( 'System', 'adminease' );
}
/**
* Renders the table rows.
*
* @param array $entries Log rows.
*
* @return string The rendered HTML rows.
*/
public function render_rows( array $entries ): string {
if( empty( $entries ) ) {
return '';
}
$labels = $this->get_event_labels();
ob_start();
foreach( $entries as $entry ) {
?>
| format_timestamp( (string) $entry['timestamp'] ) ); ?> |
get_user_label( $entry ) ); ?> |
|
describe( $entry ) ); ?> |
|
is_enabled() || !$this->table_exists() ) {
return;
}
global $wpdb;
$settings = Plugin::get_settings( 'users' );
$table = $this->get_table_name();
$periods = [
'30_days' => 30 * DAY_IN_SECONDS,
'90_days' => 90 * DAY_IN_SECONDS,
'180_days' => 180 * DAY_IN_SECONDS,
'1_year' => YEAR_IN_SECONDS,
];
$period = $settings['audit_log_auto_clear'] ?? '90_days';
if( isset( $periods[ $period ] ) ) {
$cutoff = wp_date( 'Y-m-d H:i:s', time() - $periods[ $period ] );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Scheduled log cleanup
$wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE timestamp < %s", $cutoff ) );
}
$max_entries = min( 100000, max( 100, (int) ( $settings['audit_log_max_entries'] ?? 10000 ) ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Count check for log maintenance
$count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
if( $count > $max_entries ) {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Log cleanup
$wpdb->query( $wpdb->prepare( "DELETE FROM {$table} ORDER BY id ASC LIMIT %d", $count - $max_entries ) );
}
}
/**
* Creates the log table for the site currently loaded.
*
* @return void
*/
public function create_table(): void {
global $wpdb;
$table = $this->get_table_name();
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE {$table} (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
timestamp datetime NOT NULL,
user_id bigint(20) unsigned NOT NULL DEFAULT 0,
user_login varchar(60) NOT NULL DEFAULT '',
user_ip varchar(45) NOT NULL DEFAULT '',
event varchar(20) NOT NULL DEFAULT '',
action varchar(40) NOT NULL DEFAULT '',
object_id bigint(20) unsigned NOT NULL DEFAULT 0,
object_name varchar(255) NOT NULL DEFAULT '',
details text DEFAULT NULL,
PRIMARY KEY (id),
KEY timestamp (timestamp),
KEY event (event),
KEY user_id (user_id)
) {$charset_collate};";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
update_option( self::TABLE_OPTION, '1' );
}
}