standalone: implement User fields when_last_accessed and when_updated
authorRich Lott / Artful Robot <code.commits@artfulrobot.uk>
Sun, 3 Dec 2023 13:15:47 +0000 (13:15 +0000)
committerRich Lott / Artful Robot <code.commits@artfulrobot.uk>
Sun, 3 Dec 2023 13:20:48 +0000 (13:20 +0000)
When last accessed tracks when the logged in user last
made a PHP request to the site, limited to one update per minute.

When updated tracks when a user record was updated.

ext/standaloneusers/CRM/Standaloneusers/BAO/User.php [new file with mode: 0644]
ext/standaloneusers/standaloneusers.php

diff --git a/ext/standaloneusers/CRM/Standaloneusers/BAO/User.php b/ext/standaloneusers/CRM/Standaloneusers/BAO/User.php
new file mode 100644 (file)
index 0000000..70f96fd
--- /dev/null
@@ -0,0 +1,32 @@
+<?php
+
+/**
+ * @package CRM
+ * @copyright CiviCRM LLC https://civicrm.org/licensing
+ */
+
+/**
+ * Business access object for the User entity.
+ */
+class CRM_Standaloneusers_BAO_User extends CRM_Standaloneusers_DAO_User implements \Civi\Core\HookInterface {
+
+  /**
+   * Event fired after an action is taken on a User record.
+   * @param \Civi\Core\Event\PreEvent $event
+   */
+  public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent $event) {
+    if (in_array($event->action, ['create', 'edit'])
+        && empty($event->params['when_updated'])) {
+      // Track when_updated.
+      $event->params['when_updated'] = date('YmdHis');
+    }
+  }
+
+  public static function updateLastAccessed() {
+    $sess = CRM_Core_Session::singleton();
+    $ufID = (int) $sess->get('ufID');
+    CRM_Core_DAO::executeQuery("UPDATE civicrm_uf_match SET when_last_accessed = NOW() WHERE id = $ufID");
+    $sess->set('lastAccess', time());
+  }
+
+}
index dff4299e3f3e68e0ce66074b0460c55d12c55fff..2b7b2e793125a47c886ed16e0457d5ef6de427cd 100644 (file)
@@ -17,6 +17,15 @@ use CRM_Standaloneusers_ExtensionUtil as E;
  */
 function standaloneusers_civicrm_config(&$config) {
   _standaloneusers_civix_civicrm_config($config);
+  $sess = CRM_Core_Session::singleton();
+
+  if (!empty($sess->get('ufID'))) {
+    // Logged in user is making a request.
+    if (empty($sess->get('lastAccess')) || (time() - $sess->get('lastAccess')) >= 60) {
+      // Once a minute, update the when_last_accessed field
+      CRM_Standaloneusers_BAO_User::updateLastAccessed();
+    }
+  }
 }
 
 /**