Skip to content

Commit

Permalink
Code review suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
luismulinari committed Aug 14, 2023
1 parent 5fadcf7 commit e122725
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions security/user-last-seen.php
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
<?php

const LAST_SEEN_UPDATE_USER_META_CACHE_TTL = 60; // Store last seen once per minute to avoid too much write DB operations
const LAST_SEEN_UPDATE_USER_META_CACHE_KEY_PREFIX = 'vip_last_seen_update_user_meta_cache_key';
const LAST_SEEN_UPDATE_USER_META_CACHE_TTL = 60 * 5; // Store last seen once every five minute to avoid too many write DB operations
const LAST_SEEN_UPDATE_USER_META_CACHE_KEY_PREFIX = 'wpvip_last_seen_update_user_meta_cache_key';

add_action( 'set_current_user', 'update_user_last_seen', 10, 0 );
add_filter('manage_users_columns', 'users_columns' ) ;
add_filter('manage_users_custom_column', 'users_custom_column', 10, 3 ) ;
add_filter( 'manage_users_columns', 'users_columns' ) ;
add_filter( 'manage_users_custom_column', 'users_custom_column', 10, 3 ) ;

function update_user_last_seen() {
global $current_user;

$cache_key = LAST_SEEN_UPDATE_USER_META_CACHE_KEY_PREFIX . $current_user->ID;
if ( ! $current_user->ID ) {
return;
}

try {
if ( wp_cache_get( $cache_key ) ) {
return;
}
$cache_key = LAST_SEEN_UPDATE_USER_META_CACHE_KEY_PREFIX . $current_user->ID;

update_user_meta( $current_user->ID, 'vip_last_seen', time() );
if ( wp_cache_get( $cache_key, 'wpvip' ) ) {
// Last seen meta was updated recently, no need to update it again
return;
}

wp_cache_set( $cache_key, true, null, LAST_SEEN_UPDATE_USER_META_CACHE_TTL );
} catch ( \Exception $e ) {
trigger_error(
sprintf( 'failed to update user last seen meta', esc_html( $e->getMessage() ) ),
E_USER_WARNING
);
if ( wp_cache_add( $cache_key, true, 'wpvip', LAST_SEEN_UPDATE_USER_META_CACHE_TTL ) ) {
update_user_meta( $current_user->ID, 'wpvip_last_seen', time() );
}
}

Expand All @@ -35,7 +33,7 @@ function users_columns($cols) {

function users_custom_column( $default, $column_name, $user_id ) {
if ( 'last_seen' == $column_name ) {
$last_seen_timestamp = get_user_meta( $user_id, 'vip_last_seen', true );
$last_seen_timestamp = get_user_meta( $user_id, 'wpvip_last_seen', true );

if ( $last_seen_timestamp ) {
$formatted_date = sprintf(
Expand Down

0 comments on commit e122725

Please sign in to comment.