Brak opisu

class-wc-geolocation.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. /**
  3. * Geolocation class
  4. *
  5. * Handles geolocation and updating the geolocation database.
  6. *
  7. * This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com.
  8. *
  9. * @package WooCommerce\Classes
  10. * @version 3.9.0
  11. */
  12. defined( 'ABSPATH' ) || exit;
  13. /**
  14. * WC_Geolocation Class.
  15. */
  16. class WC_Geolocation {
  17. /**
  18. * GeoLite IPv4 DB.
  19. *
  20. * @deprecated 3.4.0
  21. */
  22. const GEOLITE_DB = 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz';
  23. /**
  24. * GeoLite IPv6 DB.
  25. *
  26. * @deprecated 3.4.0
  27. */
  28. const GEOLITE_IPV6_DB = 'http://geolite.maxmind.com/download/geoip/database/GeoIPv6.dat.gz';
  29. /**
  30. * GeoLite2 DB.
  31. *
  32. * @since 3.4.0
  33. * @deprecated 3.9.0
  34. */
  35. const GEOLITE2_DB = 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz';
  36. /**
  37. * API endpoints for looking up user IP address.
  38. *
  39. * @var array
  40. */
  41. private static $ip_lookup_apis = array(
  42. 'ipify' => 'http://api.ipify.org/',
  43. 'ipecho' => 'http://ipecho.net/plain',
  44. 'ident' => 'http://ident.me',
  45. 'whatismyipaddress' => 'http://bot.whatismyipaddress.com',
  46. );
  47. /**
  48. * API endpoints for geolocating an IP address
  49. *
  50. * @var array
  51. */
  52. private static $geoip_apis = array(
  53. 'ipinfo.io' => 'https://ipinfo.io/%s/json',
  54. 'ip-api.com' => 'http://ip-api.com/json/%s',
  55. );
  56. /**
  57. * Check if geolocation is enabled.
  58. *
  59. * @since 3.4.0
  60. * @param string $current_settings Current geolocation settings.
  61. * @return bool
  62. */
  63. private static function is_geolocation_enabled( $current_settings ) {
  64. return in_array( $current_settings, array( 'geolocation', 'geolocation_ajax' ), true );
  65. }
  66. /**
  67. * Get current user IP Address.
  68. *
  69. * @return string
  70. */
  71. public static function get_ip_address() {
  72. if ( isset( $_SERVER['HTTP_X_REAL_IP'] ) ) {
  73. return sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REAL_IP'] ) );
  74. } elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
  75. // Proxy servers can send through this header like this: X-Forwarded-For: client1, proxy1, proxy2
  76. // Make sure we always only send through the first IP in the list which should always be the client IP.
  77. return (string) rest_is_ip_address( trim( current( preg_split( '/,/', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) ) ) );
  78. } elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
  79. return sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
  80. }
  81. return '';
  82. }
  83. /**
  84. * Get user IP Address using an external service.
  85. * This can be used as a fallback for users on localhost where
  86. * get_ip_address() will be a local IP and non-geolocatable.
  87. *
  88. * @return string
  89. */
  90. public static function get_external_ip_address() {
  91. $external_ip_address = '0.0.0.0';
  92. if ( '' !== self::get_ip_address() ) {
  93. $transient_name = 'external_ip_address_' . self::get_ip_address();
  94. $external_ip_address = get_transient( $transient_name );
  95. }
  96. if ( false === $external_ip_address ) {
  97. $external_ip_address = '0.0.0.0';
  98. $ip_lookup_services = apply_filters( 'woocommerce_geolocation_ip_lookup_apis', self::$ip_lookup_apis );
  99. $ip_lookup_services_keys = array_keys( $ip_lookup_services );
  100. shuffle( $ip_lookup_services_keys );
  101. foreach ( $ip_lookup_services_keys as $service_name ) {
  102. $service_endpoint = $ip_lookup_services[ $service_name ];
  103. $response = wp_safe_remote_get( $service_endpoint, array( 'timeout' => 2 ) );
  104. if ( ! is_wp_error( $response ) && rest_is_ip_address( $response['body'] ) ) {
  105. $external_ip_address = apply_filters( 'woocommerce_geolocation_ip_lookup_api_response', wc_clean( $response['body'] ), $service_name );
  106. break;
  107. }
  108. }
  109. set_transient( $transient_name, $external_ip_address, DAY_IN_SECONDS );
  110. }
  111. return $external_ip_address;
  112. }
  113. /**
  114. * Geolocate an IP address.
  115. *
  116. * @param string $ip_address IP Address.
  117. * @param bool $fallback If true, fallbacks to alternative IP detection (can be slower).
  118. * @param bool $api_fallback If true, uses geolocation APIs if the database file doesn't exist (can be slower).
  119. * @return array
  120. */
  121. public static function geolocate_ip( $ip_address = '', $fallback = false, $api_fallback = true ) {
  122. // Filter to allow custom geolocation of the IP address.
  123. $country_code = apply_filters( 'woocommerce_geolocate_ip', false, $ip_address, $fallback, $api_fallback );
  124. if ( false !== $country_code ) {
  125. return array(
  126. 'country' => $country_code,
  127. 'state' => '',
  128. 'city' => '',
  129. 'postcode' => '',
  130. );
  131. }
  132. if ( empty( $ip_address ) ) {
  133. $ip_address = self::get_ip_address();
  134. }
  135. $country_code = self::get_country_code_from_headers();
  136. /**
  137. * Get geolocation filter.
  138. *
  139. * @since 3.9.0
  140. * @param array $geolocation Geolocation data, including country, state, city, and postcode.
  141. * @param string $ip_address IP Address.
  142. */
  143. $geolocation = apply_filters(
  144. 'woocommerce_get_geolocation',
  145. array(
  146. 'country' => $country_code,
  147. 'state' => '',
  148. 'city' => '',
  149. 'postcode' => '',
  150. ),
  151. $ip_address
  152. );
  153. // If we still haven't found a country code, let's consider doing an API lookup.
  154. if ( '' === $geolocation['country'] && $api_fallback ) {
  155. $geolocation['country'] = self::geolocate_via_api( $ip_address );
  156. }
  157. // It's possible that we're in a local environment, in which case the geolocation needs to be done from the
  158. // external address.
  159. if ( '' === $geolocation['country'] && $fallback ) {
  160. $external_ip_address = self::get_external_ip_address();
  161. // Only bother with this if the external IP differs.
  162. if ( '0.0.0.0' !== $external_ip_address && $external_ip_address !== $ip_address ) {
  163. return self::geolocate_ip( $external_ip_address, false, $api_fallback );
  164. }
  165. }
  166. return array(
  167. 'country' => $geolocation['country'],
  168. 'state' => $geolocation['state'],
  169. 'city' => $geolocation['city'],
  170. 'postcode' => $geolocation['postcode'],
  171. );
  172. }
  173. /**
  174. * Path to our local db.
  175. *
  176. * @deprecated 3.9.0
  177. * @param string $deprecated Deprecated since 3.4.0.
  178. * @return string
  179. */
  180. public static function get_local_database_path( $deprecated = '2' ) {
  181. wc_deprecated_function( 'WC_Geolocation::get_local_database_path', '3.9.0' );
  182. $integration = wc()->integrations->get_integration( 'maxmind_geolocation' );
  183. return $integration->get_database_service()->get_database_path();
  184. }
  185. /**
  186. * Update geoip database.
  187. *
  188. * @deprecated 3.9.0
  189. * Extract files with PharData. Tool built into PHP since 5.3.
  190. */
  191. public static function update_database() {
  192. wc_deprecated_function( 'WC_Geolocation::update_database', '3.9.0' );
  193. $integration = wc()->integrations->get_integration( 'maxmind_geolocation' );
  194. $integration->update_database();
  195. }
  196. /**
  197. * Fetches the country code from the request headers, if one is available.
  198. *
  199. * @since 3.9.0
  200. * @return string The country code pulled from the headers, or empty string if one was not found.
  201. */
  202. private static function get_country_code_from_headers() {
  203. $country_code = '';
  204. $headers = array(
  205. 'MM_COUNTRY_CODE',
  206. 'GEOIP_COUNTRY_CODE',
  207. 'HTTP_CF_IPCOUNTRY',
  208. 'HTTP_X_COUNTRY_CODE',
  209. );
  210. foreach ( $headers as $header ) {
  211. if ( empty( $_SERVER[ $header ] ) ) {
  212. continue;
  213. }
  214. $country_code = strtoupper( sanitize_text_field( wp_unslash( $_SERVER[ $header ] ) ) );
  215. break;
  216. }
  217. return $country_code;
  218. }
  219. /**
  220. * Use APIs to Geolocate the user.
  221. *
  222. * Geolocation APIs can be added through the use of the woocommerce_geolocation_geoip_apis filter.
  223. * Provide a name=>value pair for service-slug=>endpoint.
  224. *
  225. * If APIs are defined, one will be chosen at random to fulfil the request. After completing, the result
  226. * will be cached in a transient.
  227. *
  228. * @param string $ip_address IP address.
  229. * @return string
  230. */
  231. private static function geolocate_via_api( $ip_address ) {
  232. $country_code = get_transient( 'geoip_' . $ip_address );
  233. if ( false === $country_code ) {
  234. $geoip_services = apply_filters( 'woocommerce_geolocation_geoip_apis', self::$geoip_apis );
  235. if ( empty( $geoip_services ) ) {
  236. return '';
  237. }
  238. $geoip_services_keys = array_keys( $geoip_services );
  239. shuffle( $geoip_services_keys );
  240. foreach ( $geoip_services_keys as $service_name ) {
  241. $service_endpoint = $geoip_services[ $service_name ];
  242. $response = wp_safe_remote_get( sprintf( $service_endpoint, $ip_address ), array( 'timeout' => 2 ) );
  243. if ( ! is_wp_error( $response ) && $response['body'] ) {
  244. switch ( $service_name ) {
  245. case 'ipinfo.io':
  246. $data = json_decode( $response['body'] );
  247. $country_code = isset( $data->country ) ? $data->country : '';
  248. break;
  249. case 'ip-api.com':
  250. $data = json_decode( $response['body'] );
  251. $country_code = isset( $data->countryCode ) ? $data->countryCode : ''; // @codingStandardsIgnoreLine
  252. break;
  253. default:
  254. $country_code = apply_filters( 'woocommerce_geolocation_geoip_response_' . $service_name, '', $response['body'] );
  255. break;
  256. }
  257. $country_code = sanitize_text_field( strtoupper( $country_code ) );
  258. if ( $country_code ) {
  259. break;
  260. }
  261. }
  262. }
  263. set_transient( 'geoip_' . $ip_address, $country_code, DAY_IN_SECONDS );
  264. }
  265. return $country_code;
  266. }
  267. /**
  268. * Hook in geolocation functionality.
  269. *
  270. * @deprecated 3.9.0
  271. * @return null
  272. */
  273. public static function init() {
  274. wc_deprecated_function( 'WC_Geolocation::init', '3.9.0' );
  275. return null;
  276. }
  277. /**
  278. * Prevent geolocation via MaxMind when using legacy versions of php.
  279. *
  280. * @deprecated 3.9.0
  281. * @since 3.4.0
  282. * @param string $default_customer_address current value.
  283. * @return string
  284. */
  285. public static function disable_geolocation_on_legacy_php( $default_customer_address ) {
  286. wc_deprecated_function( 'WC_Geolocation::disable_geolocation_on_legacy_php', '3.9.0' );
  287. if ( self::is_geolocation_enabled( $default_customer_address ) ) {
  288. $default_customer_address = 'base';
  289. }
  290. return $default_customer_address;
  291. }
  292. /**
  293. * Maybe trigger a DB update for the first time.
  294. *
  295. * @deprecated 3.9.0
  296. * @param string $new_value New value.
  297. * @param string $old_value Old value.
  298. * @return string
  299. */
  300. public static function maybe_update_database( $new_value, $old_value ) {
  301. wc_deprecated_function( 'WC_Geolocation::maybe_update_database', '3.9.0' );
  302. if ( $new_value !== $old_value && self::is_geolocation_enabled( $new_value ) ) {
  303. self::update_database();
  304. }
  305. return $new_value;
  306. }
  307. }