View source
<?php
namespace Drupal\ip_geoloc\Services;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Component\Utility\Html;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Component\Utility\Xss;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Render\Markup;
use Drupal\Core\Config\ConfigFactoryInterface;
define('IP_GEOLOC_GOOGLE_MAPS', ip_geoloc_build_google_api_url());
define('IP_GEOLOC_GOOGLE_MAPS_SERVER', 'https://maps.googleapis.com/maps/api/geocode/json');
class IpGeoLocAPI {
protected $logger;
protected $ipGeolocSession;
protected $stringTranslation;
protected $messenger;
protected $config;
public function __construct(LoggerChannelFactoryInterface $logger, IpGeoLocSession $ipGeolocSession, TranslationInterface $stringTranslation, MessengerInterface $messenger, ConfigFactoryInterface $config_factory) {
$this->logger = $logger;
$this->ipGeolocSession = $ipGeolocSession;
$this->stringTranslation = $stringTranslation;
$this->messenger = $messenger;
$this->config = $config_factory
->get('ip_geoloc.settings');
}
public function storeLocation(array $location) {
$config = \Drupal::config('ip_geloc.settings');
$stores_addresses = $this->config
->get('ip_geoloc_store_addresses') ? $this->config
->get('ip_geoloc_store_addresses') : TRUE;
if (!$stores_addresses) {
return;
}
if (empty($location['ip_address']) || empty($location['formatted_address'])) {
return 0;
}
if ($location['ip_address'] != '127.0.0.1' && (!isset($location['latitude']) || !isset($location['latitude']))) {
$this->logger
->get('IPGV&M')
->warning('latitude or longitude missing for IP address %ip (location still stored)', [
'%ip' => $location['ip_address'],
]);
}
$connection = \Drupal::database();
$result = $connection
->query('SELECT * FROM {ip_geoloc} WHERE ip_address = :ip', [
':ip' => $location['ip_address'],
]);
$existing_location = $result
->fetchAssoc();
if (!$existing_location) {
$location['city'] = utf8_encode($location['city']);
$location['formatted_address'] = utf8_encode($location['formatted_address']);
$full_location =& $location;
}
else {
$empty_location['latitude'] = '';
$empty_location['longitude'] = '';
$empty_location['country'] = '';
$empty_location['country_code'] = '';
$empty_location['region'] = '';
$empty_location['region_code'] = '';
$empty_location['city'] = '';
$empty_location['locality'] = '';
$empty_location['route'] = '';
$empty_location['street_number'] = '';
$empty_location['postal_code'] = '';
$empty_location['administrative_area_level_1'] = '';
$empty_location['formatted_address'] = '';
$location['id'] = $existing_location['id'];
$full_location = array_merge($empty_location, $location);
}
try {
$result = $connection
->merge('ip_geoloc')
->fields($full_location);
if ($existing_location) {
$result
->key([
'id',
]);
}
$result
->execute();
} catch (PDOException $e) {
$this->messenger
->addMessage(Html::escape($e
->getMessage()), 'error');
$result = FALSE;
}
if ($result === FALSE) {
$this->messenger
->addMessage($this->stringTranslation
->translate('IPGV&M: could not save location to db: !location', [
'!location' => ip_geoloc_pretty_print($full_location),
]), 'error');
}
return $result;
}
public function outputMap($latitude, $longitude, $div_id = 'ip-geoloc-map', $style = '', $balloon_text = '') {
drupal_add_js(IP_GEOLOC_GOOGLE_MAPS, [
'type' => 'external',
'group' => JS_LIBRARY,
]);
drupal_add_js(drupal_get_path('module', 'ip_geoloc') . '/js/ip_geoloc_gmap.js');
$script_code = "displayGMap({$latitude}, {$longitude}, '{$div_id}', '{$balloon_text}');";
drupal_add_js($script_code, [
'type' => 'inline',
'scope' => 'footer',
]);
$map_placeholder = "<div id='{$div_id}'" . (empty($style) ? '' : " style='{$style}'") . '></div>';
return $map_placeholder;
}
public function outputMapMultiVisitor($locations, $div_id = 'ip-geoloc-map-multi-locations', $map_options = NULL, $map_style = NULL) {
if (!isset($map_style)) {
$map_style = IP_GEOLOC_MAP_DIV_DEFAULT_STYLE;
}
$map_placeholder = "<div id='{$div_id}'" . (empty($map_style) ? '' : " style='{$map_style}'") . '></div>';
return $map_placeholder;
}
public function outputMapMultiLocation(array $locations, $div_id = 'ip-geoloc-map-multi-locations', $map_options = NULL, $map_style = NULL, $marker_color = NULL, $visitor_marker = TRUE, $center_option = 0, array $center_latlng = [
0,
0,
], $visitor_location_gps = TRUE) {
if (!isset($map_options)) {
$map_options = IP_GEOLOC_RECENT_VISITORS_MAP_OPTIONS;
}
$marker_directory = file_create_url(ip_geoloc_marker_directory());
$marker_dimensions = explode('x', ip_geoloc_marker_dimensions());
$marker_width = (int) $marker_dimensions[0];
$marker_height = (int) $marker_dimensions[1];
$ip_geoloc_marker_anchor_pos = $this->config
->get('ip_geoloc_marker_anchor_pos') ? $this->config
->get('ip_geoloc_marker_anchor_pos') : 'bottom';
switch ($ip_geoloc_marker_anchor_pos) {
case 'top':
$marker_anchor = 0;
break;
case 'middle':
$marker_anchor = (int) (($marker_height + 1) / 2);
break;
default:
$marker_anchor = $marker_height;
}
ip_geoloc_debug(t('IPGV&M: passing the following to Google Maps:'));
ip_geoloc_debug(t('- map options %options:', [
'%options' => $map_options,
]));
ip_geoloc_debug(t('- center option: @option', [
'@option' => $center_option,
]));
ip_geoloc_debug(t('- visitor marker: %marker', [
'%marker' => $visitor_marker,
]));
ip_geoloc_debug(t('- use GPS: @gps', [
'@gps' => (bool) $visitor_location_gps,
]));
ip_geoloc_debug(t('- visitor location fallback: (@lat, @lng)', [
'@lat' => empty($center_latlng[0]) ? '-' : $center_latlng[0],
'@lng' => empty($center_latlng[1]) ? '-' : $center_latlng[1],
]));
ip_geoloc_debug(t('- marker directory : %dir', [
'%dir' => $marker_directory,
]));
ip_geoloc_debug(t('- marker dimensions : w@w x h@h px, anchor: @a px', [
'@w' => $marker_width,
'@h' => $marker_height,
'@a' => $marker_anchor,
]));
ip_geoloc_debug(t('- @count locations found', [
'@count' => count($locations),
]));
$output = "\n<script>\nif (typeof(ip_geoloc_locations) === 'undefined') {\n ip_geoloc_locations = new Array();\n}\n";
$output .= "ip_geoloc_locations['{$div_id}'] = [\n";
$illegal_chars = [
"\n",
"\r",
];
foreach ($locations as $location) {
if (isset($location->type) && $location->type != 'point') {
continue;
}
$balloon_text = NULL;
if (!empty($location->balloon_text)) {
$balloon_text = str_replace($illegal_chars, ' ', $location->balloon_text);
$balloon_text = addslashes($balloon_text);
}
$output .= '{"type":"point"' . (empty($location->marker_color) ? '' : ',"marker_color":"' . $location->marker_color . '"') . (empty($balloon_text) ? '' : ',"balloon_text":"' . $balloon_text . '"') . (empty($location->open) ? '' : ',"open":1') . ',"latitude":' . $location->latitude . ',"longitude":' . $location->longitude . "},\n";
$color = empty($location->marker_color) ? t('default') . " [{$marker_color}]" : $location->marker_color;
$coords = isset($location->latitude) ? $location->latitude . ', ' . $location->longitude : '';
$msg = '- ' . t('marker') . " {$color} ({$coords})<br/>{$balloon_text}<br/>";
ip_geoloc_debug($msg);
}
$output .= "];\n</script>\n";
$settings = [
'ip_geoloc_multi_location_map_div' => $div_id,
'ip_geoloc_multi_location_map_options' => Json::decode($map_options),
'ip_geoloc_multi_location_center_option' => (int) $center_option,
'ip_geoloc_multi_location_center_latlng' => $center_latlng,
'ip_geoloc_multi_location_visitor_marker' => $visitor_marker,
'ip_geoloc_multi_location_visitor_location_gps' => $visitor_location_gps,
'ip_geoloc_multi_location_marker_directory' => $marker_directory,
'ip_geoloc_multi_location_marker_width' => (int) $marker_width,
'ip_geoloc_multi_location_marker_height' => (int) $marker_height,
'ip_geoloc_multi_location_marker_anchor' => (int) $marker_anchor,
'ip_geoloc_multi_location_marker_default_color' => $marker_color,
'ip_geoloc_locations' => $locations,
];
if (!isset($map_style)) {
$map_style = IP_GEOLOC_MAP_DIV_DEFAULT_STYLE;
}
$map_placeholder = "<div id='{$div_id}'" . (empty($map_style) ? '' : " style='{$map_style}'") . '></div>';
$items_array = [
'#theme' => 'ip_geoloc_map',
'#ip_geoloc_output_map_multi_location' => [
'#markup' => Markup::create($map_placeholder),
],
];
$items_array['#attached']['html_head'][] = [
[
'#type' => 'html_tag',
'#tag' => 'script',
'#value' => $output,
],
];
$items_array['#attached']['library'][] = 'ip_geoloc/multi_location_js_style_map';
$items_array['#attached']['drupalSettings'] = $settings;
return \Drupal::service('renderer')
->render($items_array);
}
public function getCurrentLocation($menu_callback = NULL, $reverse_geocode = NULL, $refresh_page = NULL) {
$config = \Drupal::config('ip_geoloc.settings');
$throbber_text = $this->config
->get('ip_geoloc_throbber_text2');
if (empty($throbber_text)) {
$throbber_text = IP_GEOLOC_THROBBER_DEFAULT_TEXT;
}
if ($throbber_text != '<none>') {
$this->messenger
->addMessage(Xss::filterAdmin($throbber_text));
}
$this->ipGeolocSession
->setSessionValue('last_position_check', time());
$this->ipGeolocSession
->setSessionValue('position_pending_since', microtime(TRUE));
if (!isset($menu_callback)) {
$base_url = \Drupal::request()
->getSchemeAndHttpHost();
$menu_callback = "{$base_url}/" . 'js/ip_geoloc/current_location';
}
if (!isset($reverse_geocode)) {
$reverse_geocode = $this->config
->get('ip_geoloc_visitor_reverse_geocode') ? $this->config
->get('ip_geoloc_visitor_reverse_geocode') : TRUE;
}
if (!isset($refresh_page)) {
$refresh_page = $this->config
->get('ip_geoloc_page_refresh') ? $this->config
->get('ip_geoloc_visitor_reverse_geocode') : TRUE && !path_is_admin($_GET['q']);
}
$settings = [
'ip_geoloc_menu_callback' => $menu_callback,
'ip_geoloc_refresh_page' => $refresh_page,
'ip_geoloc_reverse_geocode' => $reverse_geocode,
];
return $settings;
}
public function getLocationByIp($ip_address, $resample = FALSE, $store = FALSE, $reverse_geocode = NULL) {
$location = $resample ? NULL : db_query('SELECT * FROM {ip_geoloc} WHERE ip_address = :ip_address', [
':ip_address' => $ip_address,
])
->fetchAssoc();
if (empty($location)) {
$location = [
'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 = $this->config
->get('ip_geoloc_google_to_reverse_geocode') ? $this->config
->get('ip_geoloc_google_to_reverse_geocode') : FALSE;
}
if ($reverse_geocode && isset($location['latitude']) && isset($location['longitude'])) {
if ($google_address = $this
->reverseGeocode($location['latitude'], $location['longitude'])) {
ip_geoloc_flatten_google_address($google_address, $location);
}
}
if ($store) {
ip_geoloc_store_location($location);
}
else {
drupal_alter('get_ip_geolocation', $location);
}
}
}
return $location;
}
public function getAddress($latitude, $longitude, $lang = NULL) {
return $google_address = $this
->reverseGeocode($latitude, $longitude, $lang) ? $google_address['formatted_address'] : '';
}
public function reverseGeocode($latitude, $longitude, $lang = NULL) {
if (empty($latitude) || empty($latitude)) {
drupal_set_message(t('IPGV&M: cannot reverse-geocode to address as no lat/long was specified.'), 'warning');
return FALSE;
}
$query_start = microtime(TRUE);
$url = IP_GEOLOC_GOOGLE_MAPS_SERVER . "?latlng={$latitude},{$longitude}";
if (!empty($lang)) {
$url .= "&language={$lang}";
}
$response = drupal_http_request($url);
if (!empty($response->error)) {
$msg_args = [
'%url' => $url,
'@code' => $response->code,
'%error' => $response->error,
];
drupal_set_message(t('IPGV&M: the HTTP request %url returned the following error (code @code): %error.', $msg_args), 'error');
watchdog('IPGV&M', 'Error (code @code): %error. Request: %url', $msg_args, WATCHDOG_ERROR);
return FALSE;
}
$data = drupal_json_decode($response->data);
if ($data['status'] == 'OVER_QUERY_LIMIT') {
$msg_args = [
'%url' => $url,
];
if (user_access('administer site configuration')) {
drupal_set_message(t('IPGV&M: Server is over its query limit. Request: %url', $msg_args), 'error');
}
watchdog('IPGV&M', 'Server is over its query limit. Request: %url', $msg_args, WATCHDOG_ERROR);
return FALSE;
}
if ($data['status'] == 'ZERO_RESULTS' || !isset($data['results'][0])) {
$msg_args = [
'@protocol' => $response->protocol,
'%url' => $url,
];
drupal_set_message(t('IPGV&M: the @protocol request %url succeeded, but returned no results.', $msg_args), 'warning');
watchdog('IPGV&M', 'No results from @protocol request %url.', $msg_args, WATCHDOG_WARNING);
return FALSE;
}
if ($data['status'] != 'OK') {
$msg_args = [
'%url' => $url,
'%error' => $data['status'],
];
drupal_set_message(t('IPGV&M: unknown error %error. Request: %url..', $msg_args), 'error');
watchdog('IPGV&M', 'Unknown error %error. Request: %url.', $msg_args, WATCHDOG_ERROR);
return FALSE;
}
$google_address = $data['results'][0];
if (empty($google_address['formatted_address'])) {
$msg_args = [
'@lat' => $latitude,
'@long' => $longitude,
];
ip_geoloc_debug(t('IPGV&M: (@lat, @long) could not be reverse-geocoded to a street address.', $msg_args), 'warning');
watchdog('IPGV&M', '(@lat, @long) could not be reverse-geocoded to a street address..', $msg_args, WATCHDOG_WARNING);
}
else {
$sec = number_format(microtime(TRUE) - $query_start, 1);
$msg_args = [
'@lat' => $latitude,
'@long' => $longitude,
'%sec' => $sec,
'%address' => $google_address['formatted_address'],
];
ip_geoloc_debug(t('IPGV&M: %address reverse-geocoded from (@lat, @long) in %sec s.', $msg_args));
watchdog('IPGV&M', '%address reverse-geocoded from (@lat, @long) in %sec s.', $msg_args, WATCHDOG_INFO);
}
return $google_address;
}
public function getVisitorLocation() {
$location = $this->ipGeolocSession
->getSessionValue('location');
return $location;
}
public function centerOfLocations(array $locations, $center_of_gravity = FALSE) {
if (empty($locations)) {
return [
NULL,
NULL,
];
}
if ($center_of_gravity) {
$count = 0;
$x = $y = $z = 0.0;
foreach ($locations as $location) {
if (isset($location->lon)) {
$lng = $location->lon;
$lat = $location->lat;
}
elseif (isset($location->longitude)) {
$lng = $location->longitude;
$lat = $location->latitude;
}
else {
continue;
}
$lng = deg2rad($lng);
$lat = deg2rad($lat);
$x += cos($lat) * cos($lng);
$y += cos($lat) * sin($lng);
$z += sin($lat);
$count++;
}
$x /= $count;
$y /= $count;
$z /= $count;
$center_lat = atan2($z, sqrt($x * $x + $y * $y));
$center_lng = atan2($y, $x);
return [
rad2deg($center_lat),
rad2deg($center_lng),
];
}
$top = $bottom = $left = $right = NULL;
foreach ($locations as $location) {
if (isset($location->lon)) {
$lng = $location->lon;
$lat = $location->lat;
}
elseif (isset($location->longitude)) {
$lng = $location->longitude;
$lat = $location->latitude;
}
else {
continue;
}
if (!isset($top) || $lat > $top) {
$top = $lat;
}
if (!isset($bottom) || $lat < $bottom) {
$bottom = $lat;
}
if (!isset($left) || $lng < $left) {
$left = $lng;
}
if (!isset($right) || $lng > $right) {
$right = $lng;
}
}
if (!isset($top) || !isset($left)) {
return [
NULL,
NULL,
];
}
$center_lat = 0.5 * ($top + $bottom);
$center_lng = 0.5 * ($left + $right);
if ($right - $left > 180) {
$center_lng = $center_lng > 0.0 ? $center_lng - 180.0 : $center_lng + 180.0;
}
return [
$center_lat,
$center_lng,
];
}
public function distance(array $location, $ref_location = 'current visitor') {
if (!is_array($ref_location)) {
$ref_location = $this
->getVisitorLocation();
}
if (empty($ref_location)) {
return '?';
}
if (is_numeric($location['longitude']) && is_numeric($location['latitude']) && is_numeric($ref_location['longitude']) && is_numeric($ref_location['latitude'])) {
return ip_geoloc_earth_distance($location['longitude'], $location['latitude'], $ref_location['longitude'], $ref_location['latitude']);
}
return '?';
}
public function earthDistance($longitude1, $latitude1, $longitude2, $latitude2) {
$long1 = deg2rad($longitude1);
$lat1 = deg2rad($latitude1);
$long2 = deg2rad($longitude2);
$lat2 = deg2rad($latitude2);
$long_factor = cos($long1 - $long2);
$cosangle = cos($lat1) * cos($lat2) * $long_factor + sin($lat1) * sin($lat2);
$radius = ip_geoloc_earth_radius(0.5 * ($latitude1 + $latitude2));
$distance = acos($cosangle) * $radius;
return $distance;
}
public function earthRadius($latitude) {
$lat = deg2rad($latitude);
$x = cos($lat) / $this
->earthRadiusSemimajor();
$y = sin($lat) / $this
->earthRadiusSemiminor();
return 1.0 / sqrt($x * $x + $y * $y);
}
public function earthRadiusSemimajor() {
return 6378137.0;
}
public function earthRadiusSemiminor() {
return ip_geoloc_earth_radius_semimajor() * (1.0 - ip_geoloc_earth_flattening());
}
public function earthFlattening() {
return 1.0 / 298.257223563;
}
public function addRandomDisplacement(array &$location, $radius_km) {
$a = ip_geoloc_random(0, 1);
$b = ip_geoloc_random(0, 1);
if ($b < $a) {
$c = $a;
$a = $b;
$b = $c;
}
$angle = 2 * pi() * $a / $b;
$radius = $radius_km / 111000;
$location['lat'] += $b * $radius * cos($angle);
$location['lon'] += $b * $radius * sin($angle);
}
public function ipGeoLocRandom($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
}