You are here

function _ip_geoloc_statistics_backfill in IP Geolocation Views & Maps 8

Same name and namespace in other branches
  1. 7 plugins/ip_geoloc.statistics.inc \_ip_geoloc_statistics_backfill()

Backfills position information to past {accesslog} entries.

Given that location information is received asynchronously, here we 'backfill' such information to all accesslog entries since when the location request was initiated.

Parameters

int $from_timestamp: The timestamp of the location request.

array $location: The location infromation array.

File

plugins/ip_geoloc.statistics.inc, line 422
Capture IP Geoloc statistics in the access log.

Code

function _ip_geoloc_statistics_backfill($from_timestamp, array $location) {

  // If Better Statistics is set to skip logging to the database, then exit now.
  if (!\Drupal::state()
    ->get('statistics_log_to_db', TRUE)) {
    return;
  }

  // Fetch the database fields currently active for {accesslog}.
  $accesslog_db_fields = \Drupal::state()
    ->get('better_statistics_fields', better_statistics_get_default_fields());

  // Fetch the database fields managed by ip_geoloc.
  $ip_geoloc_db_fields = array_keys(_ip_geoloc_key_map());

  // Builds the db fields and values required for the update. Only collects
  // the values for fields currently active in {accesslog}.
  $db_fields = [];
  foreach ($ip_geoloc_db_fields as $i => $db_field_name) {
    if (isset($accesslog_db_fields[$db_field_name])) {
      $db_fields[$db_field_name] = _ip_geoloc_get_location_field_value($db_field_name, $location);
    }
  }

  // Run update. Take one extra second to from_timestamp to ensure initial hit,
  // requesting location services, is included.
  if (!empty($db_fields)) {
    try {
      $num_updated = db_update('accesslog')
        ->fields($db_fields)
        ->condition('timestamp', $from_timestamp - 1, '>=')
        ->condition('sid', session_id(), '=')
        ->execute();
    } catch (Exception $e) {
      watchdog('IPGV&M', 'There was an error updating statistics data:<br/>@error', [
        '@error' => $e
          ->getMessage(),
      ], WATCHDOG_ERROR);
    }
  }
}