| 1 |
<?php |
| 2 |
/** |
| 3 |
* Users app — last-login tracker. |
| 4 |
* |
| 5 |
* Hooks `wp_login` to record the timestamp of every successful |
| 6 |
* login as `_desktop_mode_last_login_at` user meta (a UTC unix |
| 7 |
* timestamp, stored as integer). The `openstation_last_login` REST |
| 8 |
* field surfaces this back to the table for the Last login column. |
| 9 |
* |
| 10 |
* The meta key is intentionally underscore-prefixed (private) so |
| 11 |
* it doesn't show up in user-meta-management UIs but still allows |
| 12 |
* `update_user_meta` access. Plugins that want to read the value: |
| 13 |
* |
| 14 |
* $ts = (int) get_user_meta( $user_id, OPENSTATION_LAST_LOGIN_META_KEY, true ); |
| 15 |
* |
| 16 |
* @package OpenStation |
| 17 |
*/ |
| 18 |
|
| 19 |
defined( 'ABSPATH' ) || exit; |
| 20 |
|
| 21 |
/** |
| 22 |
* The user meta key carrying the last successful login's UTC unix |
| 23 |
* timestamp. Public surface — exposed so other plugins can read / |
| 24 |
* sort by it. |
| 25 |
* |
| 26 |
* The VALUE keeps its pre-rebrand spelling on purpose: it is a |
| 27 |
* persisted identifier, so renaming it would orphan data already |
| 28 |
* written by live installs. The mismatch between this constant's |
| 29 |
* name and its value is deliberate — it is NOT a half-finished rename. |
| 30 |
*/ |
| 31 |
const OPENSTATION_LAST_LOGIN_META_KEY = '_desktop_mode_last_login_at'; |
| 32 |
|
| 33 |
/** |
| 34 |
* Record the login timestamp on every `wp_login` action. |
| 35 |
* |
| 36 |
* `wp_login` fires AFTER credentials have been validated and the |
| 37 |
* cookie set. We record server time (`time()`), which is always UTC |
| 38 |
* by convention in PHP — match it on the read side. |
| 39 |
* |
| 40 |
* @param string $user_login Login of the user. |
| 41 |
* @param WP_User $user The user object. |
| 42 |
*/ |
| 43 |
function openstation_users_window_record_login( $user_login, $user = null ) { |
| 44 |
$user_id = 0; |
| 45 |
if ( $user instanceof WP_User ) { |
| 46 |
$user_id = (int) $user->ID; |
| 47 |
} elseif ( is_string( $user_login ) && '' !== $user_login ) { |
| 48 |
$by = get_user_by( 'login', $user_login ); |
| 49 |
if ( $by instanceof WP_User ) { |
| 50 |
$user_id = (int) $by->ID; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
if ( $user_id <= 0 ) { |
| 55 |
return; |
| 56 |
} |
| 57 |
|
| 58 |
update_user_meta( $user_id, OPENSTATION_LAST_LOGIN_META_KEY, time() ); |
| 59 |
|
| 60 |
/** |
| 61 |
* Fires after the last-login meta has been written. Lets plugins |
| 62 |
* piggy-back on the same hook to update their own last-seen |
| 63 |
* tracking without duplicating the `wp_login` listener. |
| 64 |
* |
| 65 |
* @param int $user_id User id whose login was recorded. |
| 66 |
* @param int $timestamp Unix timestamp written. |
| 67 |
*/ |
| 68 |
do_action( 'openstation_users_window_login_recorded', $user_id, time() ); |
| 69 |
} |
| 70 |
add_action( 'wp_login', 'openstation_users_window_record_login', 10, 2 ); |
| 71 |
|