You are here

public static function SmartIp::query in Smart IP 8.4

Same name and namespace in other branches
  1. 8.2 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.

3 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 or debug mode IP.
SmartIpAdminSettingsForm::manualLookup in src/Form/SmartIpAdminSettingsForm.php
Submit handler to lookup an IP address in the database.
smart_ip_entity_insert in ./smart_ip.module
Implements hook_entity_insert().

File

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

Class

SmartIp
Smart IP static basic methods wrapper.

Namespace

Drupal\smart_ip

Code

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

  // Skip querying if IP address is in exclude list
  $excludedIps = \Drupal::configFactory()
    ->get('smart_ip.settings')
    ->get('excluded_ips');
  if (!empty($excludedIps)) {
    $patternsQuoted = preg_quote($excludedIps, '/');
    $patterns = '/^(' . preg_replace('/(\\r\\n?|\\n)/', '|', $patternsQuoted) . ')$/';
    if ((bool) preg_match($patterns, $ip)) {
      return array();
    }
  }

  // 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)
    ->set('ipAddress', $ip)
    ->set('ipVersion', self::ipAddressVersion($ip))
    ->set('timestamp', \Drupal::time()
    ->getRequestTime());

  // Allow Smart IP source module populate the variable.
  \Drupal::service('event_dispatcher')
    ->dispatch(SmartIpEvents::QUERY_IP, $event);
  $result = $location
    ->getData(FALSE);
  self::updateFields($result);
  $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(FALSE);
  $results[$ip] = $result;
  return $result;
}