You are here

public static function SmartIp::query in Smart IP 8.2

Same name and namespace in other branches
  1. 8.4 src/SmartIp.php \Drupal\smart_ip\SmartIp::query()
  2. 8.3 src/SmartIp.php \Drupal\smart_ip\SmartIp::query()

Get the geolocation from the IP address

Parameters

string $ip: IP address to query for geolocation. It will use current user's IP address if empty.

Return value

array Geolocation details of queried IP address.

5 calls to SmartIp::query()
SmartIp::updateUserLocation in src/SmartIp.php
Update user's location only if the IP address stored in session is not the same as the IP address detected by the server.
SmartIpAdminSettingsForm::manualLookup in src/Form/SmartIpAdminSettingsForm.php
Submit handler to lookup an IP address in the database.
SmartIpAdminSettingsForm::submitForm in src/Form/SmartIpAdminSettingsForm.php
Form submission handler.
smart_ip_entity_insert in ./smart_ip.module
Implements hook_entity_insert().
smart_ip_user_login in ./smart_ip.module
Implements hook_user_login().

File

src/SmartIp.php, line 26
Contains \Drupal\smart_ip\SmartIp.

Class

SmartIp
Smart IP static basic methods wrapper.

Namespace

Drupal\smart_ip

Code

public static function query($ip = NULL) {
  if (empty($ip)) {
    $ip = \Drupal::request()
      ->getClientIp();
  }

  // Use a static cache if this function is called more often
  // for the same ip on the same page.
  $results =& drupal_static(__FUNCTION__);
  if (isset($results[$ip])) {
    return $results[$ip];
  }

  /** @var \Drupal\smart_ip\GetLocationEvent $event */
  $event = \Drupal::service('smart_ip.get_location_event');
  $location = $event
    ->getLocation();
  $location
    ->set('source', SmartIpLocationInterface::SMART_IP);
  $location
    ->set('ipAddress', $ip);
  $location
    ->set('timestamp', REQUEST_TIME);

  // Allow Smart IP source module populate the variable
  \Drupal::service('event_dispatcher')
    ->dispatch(SmartIpEvents::QUERY_IP, $event);
  $result = $location
    ->getData();
  if (isset($result['latitude']) && isset($result['longitude'])) {

    // If coordinates are (0, 0) there was no match
    if ($result['latitude'] === 0 && $result['longitude'] === 0) {
      $result['latitude'] = NULL;
      $result['longitude'] = NULL;
    }
  }

  // Make sure external data in UTF-8.
  foreach ($result as &$item) {
    if (is_string($item) && !mb_detect_encoding($item, 'UTF-8', TRUE)) {
      $item = mb_convert_encoding($item, 'UTF-8', 'ISO-8859-1');
    }
  }
  $location
    ->setData($result);

  // Allow other modules to modify the result via Symfony Event Dispatcher
  \Drupal::service('event_dispatcher')
    ->dispatch(SmartIpEvents::DATA_ACQUIRED, $event);
  $result = $location
    ->getData();
  $results[$ip] = $result;
  return $result;
}