You are here

function ip_geoloc_get_location_by_ip in IP Geolocation Views & Maps 8

Same name and namespace in other branches
  1. 7 ip_geoloc_api.inc \ip_geoloc_get_location_by_ip()

Returns the location details associated with the supplied IP address.

Performs a lookup in IPGV&M's own database to see if the supplied IP address has visited already and if so returns their location details (as an array). If the IP address is not yet in the IP geolocation database, then retrieve lat/long using either Smart IP or GeoIP API (if enabled) and reverse-geocode the lat/long (if the Google Maps service is enabled) into a location. If the third argument is TRUE, then store the new location.

Parameters

string $ip_address: The IP address to locate

bool $resample: if set to TRUE, ignore any existing location data for this IP address and retrieve the latest

bool $store: if TRUE, store the new or resampled location on the db

bool|null $reverse_geocode: applies only when the supplied IP address is not yet on the database or $resample=TRUE; use TRUE, FALSE or NULL; TRUE will produce greater detail in the location returned; if NULL or omitted the value is taken from the tick box on the IP Geolocation configuration page. Reverse-geocoding is subject to a Google-imposed limit of 2500 calls per day from the same server IP address.

Return value

array location as an array

File

./ip_geoloc_api.inc, line 424
API functions of IP geolocation module

Code

function ip_geoloc_get_location_by_ip($ip_address, $resample = FALSE, $store = FALSE, $reverse_geocode = NULL) {
  $location = $resample ? NULL : db_query('SELECT * FROM {ip_geoloc} WHERE ip_address = :ip_address', array(
    ':ip_address' => $ip_address,
  ))
    ->fetchAssoc();
  if (empty($location)) {
    $location = array(
      'ip_address' => $ip_address,
    );
    if (ip_geoloc_use_smart_ip_if_enabled($location) || ip_geoloc_use_geoip_api_if_enabled($location)) {
      if (!isset($reverse_geocode)) {
        $reverse_geocode = \Drupal::state()
          ->get('ip_geoloc_google_to_reverse_geocode', FALSE);
      }
      if ($reverse_geocode && isset($location['latitude']) && isset($location['longitude'])) {
        if ($google_address = ip_geoloc_reverse_geocode($location['latitude'], $location['longitude'])) {

          // Should we clear out whatever Smart IP or GeoIP put in the $location
          // to avoid fields contradicting eachother? Eg. Google normally
          // returns 'locality', whereas Smart IP and GeoIP return 'city'.
          // $location = array('ip_address' => $ip_address);
          ip_geoloc_flatten_google_address($google_address, $location);
        }
      }
      if ($store) {

        // Calls drupal_alter().
        ip_geoloc_store_location($location);
      }
      else {
        drupal_alter('get_ip_geolocation', $location);
      }
    }
  }
  return $location;
}