class-wc-geolocation.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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.4.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. */
  34. const GEOLITE2_DB = 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz';
  35. /**
  36. * API endpoints for looking up user IP address.
  37. *
  38. * @var array
  39. */
  40. private static $ip_lookup_apis = array(
  41. 'icanhazip' => 'http://icanhazip.com',
  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 server supports MaxMind GeoLite2 Reader.
  58. *
  59. * @since 3.4.0
  60. * @return bool
  61. */
  62. private static function supports_geolite2() {
  63. return version_compare( PHP_VERSION, '5.4.0', '>=' );
  64. }
  65. /**
  66. * Check if geolocation is enabled.
  67. *
  68. * @since 3.4.0
  69. * @param string $current_settings Current geolocation settings.
  70. * @return bool
  71. */
  72. private static function is_geolocation_enabled( $current_settings ) {
  73. return in_array( $current_settings, array( 'geolocation', 'geolocation_ajax' ), true );
  74. }
  75. /**
  76. * Prevent geolocation via MaxMind when using legacy versions of php.
  77. *
  78. * @since 3.4.0
  79. * @param string $default_customer_address current value.
  80. * @return string
  81. */
  82. public static function disable_geolocation_on_legacy_php( $default_customer_address ) {
  83. if ( self::is_geolocation_enabled( $default_customer_address ) ) {
  84. $default_customer_address = 'base';
  85. }
  86. return $default_customer_address;
  87. }
  88. /**
  89. * Hook in geolocation functionality.
  90. */
  91. public static function init() {
  92. if ( self::supports_geolite2() ) {
  93. // Only download the database from MaxMind if the geolocation function is enabled, or a plugin specifically requests it.
  94. if ( self::is_geolocation_enabled( get_option( 'woocommerce_default_customer_address' ) ) || apply_filters( 'woocommerce_geolocation_update_database_periodically', false ) ) {
  95. add_action( 'woocommerce_geoip_updater', array( __CLASS__, 'update_database' ) );
  96. }
  97. // Trigger database update when settings are changed to enable geolocation.
  98. add_filter( 'pre_update_option_woocommerce_default_customer_address', array( __CLASS__, 'maybe_update_database' ), 10, 2 );
  99. } else {
  100. add_filter( 'pre_option_woocommerce_default_customer_address', array( __CLASS__, 'disable_geolocation_on_legacy_php' ) );
  101. }
  102. }
  103. /**
  104. * Maybe trigger a DB update for the first time.
  105. *
  106. * @param string $new_value New value.
  107. * @param string $old_value Old value.
  108. * @return string
  109. */
  110. public static function maybe_update_database( $new_value, $old_value ) {
  111. if ( $new_value !== $old_value && self::is_geolocation_enabled( $new_value ) ) {
  112. self::update_database();
  113. }
  114. return $new_value;
  115. }
  116. /**
  117. * Get current user IP Address.
  118. *
  119. * @return string
  120. */
  121. public static function get_ip_address() {
  122. if ( isset( $_SERVER['HTTP_X_REAL_IP'] ) ) { // WPCS: input var ok, CSRF ok.
  123. return sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REAL_IP'] ) ); // WPCS: input var ok, CSRF ok.
  124. } elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { // WPCS: input var ok, CSRF ok.
  125. // Proxy servers can send through this header like this: X-Forwarded-For: client1, proxy1, proxy2
  126. // Make sure we always only send through the first IP in the list which should always be the client IP.
  127. return (string) rest_is_ip_address( trim( current( preg_split( '/,/', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) ) ) ); // WPCS: input var ok, CSRF ok.
  128. } elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // @codingStandardsIgnoreLine
  129. return sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ); // @codingStandardsIgnoreLine
  130. }
  131. return '';
  132. }
  133. /**
  134. * Get user IP Address using an external service.
  135. * This is used mainly as a fallback for users on localhost where
  136. * get_ip_address() will be a local IP and non-geolocatable.
  137. *
  138. * @return string
  139. */
  140. public static function get_external_ip_address() {
  141. $external_ip_address = '0.0.0.0';
  142. if ( '' !== self::get_ip_address() ) {
  143. $transient_name = 'external_ip_address_' . self::get_ip_address();
  144. $external_ip_address = get_transient( $transient_name );
  145. }
  146. if ( false === $external_ip_address ) {
  147. $external_ip_address = '0.0.0.0';
  148. $ip_lookup_services = apply_filters( 'woocommerce_geolocation_ip_lookup_apis', self::$ip_lookup_apis );
  149. $ip_lookup_services_keys = array_keys( $ip_lookup_services );
  150. shuffle( $ip_lookup_services_keys );
  151. foreach ( $ip_lookup_services_keys as $service_name ) {
  152. $service_endpoint = $ip_lookup_services[ $service_name ];
  153. $response = wp_safe_remote_get( $service_endpoint, array( 'timeout' => 2 ) );
  154. if ( ! is_wp_error( $response ) && rest_is_ip_address( $response['body'] ) ) {
  155. $external_ip_address = apply_filters( 'woocommerce_geolocation_ip_lookup_api_response', wc_clean( $response['body'] ), $service_name );
  156. break;
  157. }
  158. }
  159. set_transient( $transient_name, $external_ip_address, WEEK_IN_SECONDS );
  160. }
  161. return $external_ip_address;
  162. }
  163. /**
  164. * Geolocate an IP address.
  165. *
  166. * @param string $ip_address IP Address.
  167. * @param bool $fallback If true, fallbacks to alternative IP detection (can be slower).
  168. * @param bool $api_fallback If true, uses geolocation APIs if the database file doesn't exist (can be slower).
  169. * @return array
  170. */
  171. public static function geolocate_ip( $ip_address = '', $fallback = true, $api_fallback = true ) {
  172. // Filter to allow custom geolocation of the IP address.
  173. $country_code = apply_filters( 'woocommerce_geolocate_ip', false, $ip_address, $fallback, $api_fallback );
  174. if ( false === $country_code ) {
  175. // If GEOIP is enabled in CloudFlare, we can use that (Settings -> CloudFlare Settings -> Settings Overview).
  176. if ( ! empty( $_SERVER['HTTP_CF_IPCOUNTRY'] ) ) { // WPCS: input var ok, CSRF ok.
  177. $country_code = strtoupper( sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_IPCOUNTRY'] ) ) ); // WPCS: input var ok, CSRF ok.
  178. } elseif ( ! empty( $_SERVER['GEOIP_COUNTRY_CODE'] ) ) { // WPCS: input var ok, CSRF ok.
  179. // WP.com VIP has a variable available.
  180. $country_code = strtoupper( sanitize_text_field( wp_unslash( $_SERVER['GEOIP_COUNTRY_CODE'] ) ) ); // WPCS: input var ok, CSRF ok.
  181. } elseif ( ! empty( $_SERVER['HTTP_X_COUNTRY_CODE'] ) ) { // WPCS: input var ok, CSRF ok.
  182. // VIP Go has a variable available also.
  183. $country_code = strtoupper( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_COUNTRY_CODE'] ) ) ); // WPCS: input var ok, CSRF ok.
  184. } else {
  185. $ip_address = $ip_address ? $ip_address : self::get_ip_address();
  186. $database = self::get_local_database_path();
  187. if ( self::supports_geolite2() && file_exists( $database ) ) {
  188. $country_code = self::geolocate_via_db( $ip_address, $database );
  189. } elseif ( $api_fallback ) {
  190. $country_code = self::geolocate_via_api( $ip_address );
  191. } else {
  192. $country_code = '';
  193. }
  194. if ( ! $country_code && $fallback ) {
  195. // May be a local environment - find external IP.
  196. return self::geolocate_ip( self::get_external_ip_address(), false, $api_fallback );
  197. }
  198. }
  199. }
  200. return array(
  201. 'country' => $country_code,
  202. 'state' => '',
  203. );
  204. }
  205. /**
  206. * Path to our local db.
  207. *
  208. * @param string $deprecated Deprecated since 3.4.0.
  209. * @return string
  210. */
  211. public static function get_local_database_path( $deprecated = '2' ) {
  212. $upload_dir = wp_upload_dir();
  213. return apply_filters( 'woocommerce_geolocation_local_database_path', $upload_dir['basedir'] . '/GeoLite2-Country.mmdb', $deprecated );
  214. }
  215. /**
  216. * Update geoip database.
  217. */
  218. public static function update_database() {
  219. $logger = wc_get_logger();
  220. if ( ! self::supports_geolite2() ) {
  221. $logger->notice( 'Requires PHP 5.4 to be able to download MaxMind GeoLite2 database', array( 'source' => 'geolocation' ) );
  222. return;
  223. }
  224. require_once ABSPATH . 'wp-admin/includes/file.php';
  225. $upload_dir = wp_upload_dir();
  226. $tmp_database_path = download_url( self::GEOLITE2_DB );
  227. if ( ! is_wp_error( $tmp_database_path ) ) {
  228. try {
  229. // GeoLite2 database name.
  230. $database = 'GeoLite2-Country.mmdb';
  231. $dest_path = trailingslashit( $upload_dir['basedir'] ) . $database;
  232. // Extract files with PharData. Tool built into PHP since 5.3.
  233. $file = new PharData( $tmp_database_path ); // phpcs:ignore PHPCompatibility.PHP.NewClasses.phardataFound
  234. $file_path = trailingslashit( $file->current()->getFileName() ) . $database;
  235. // Extract under uploads directory.
  236. $file->extractTo( $upload_dir['basedir'], $file_path, true );
  237. // Remove old database.
  238. @unlink( $dest_path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.VIP.FileSystemWritesDisallow.file_ops_unlink
  239. // Copy database and delete tmp directories.
  240. @rename( trailingslashit( $upload_dir['basedir'] ) . $file_path, $dest_path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.VIP.FileSystemWritesDisallow.file_ops_rename
  241. @rmdir( trailingslashit( $upload_dir['basedir'] ) . $file->current()->getFileName() ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.VIP.FileSystemWritesDisallow.directory_rmdir
  242. // Set correct file permission.
  243. @chmod( $dest_path, 0644 ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.VIP.FileSystemWritesDisallow.chmod_chmod
  244. } catch ( Exception $e ) {
  245. $logger->notice( $e->getMessage(), array( 'source' => 'geolocation' ) );
  246. // Reschedule download of DB.
  247. wp_clear_scheduled_hook( 'woocommerce_geoip_updater' );
  248. wp_schedule_event( strtotime( 'first tuesday of next month' ), 'monthly', 'woocommerce_geoip_updater' );
  249. }
  250. @unlink( $tmp_database_path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.VIP.FileSystemWritesDisallow.file_ops_unlink
  251. } else {
  252. $logger->notice(
  253. 'Unable to download GeoIP Database: ' . $tmp_database_path->get_error_message(),
  254. array( 'source' => 'geolocation' )
  255. );
  256. }
  257. }
  258. /**
  259. * Use MAXMIND GeoLite database to geolocation the user.
  260. *
  261. * @param string $ip_address IP address.
  262. * @param string $database Database path.
  263. * @return string
  264. */
  265. private static function geolocate_via_db( $ip_address, $database ) {
  266. if ( ! class_exists( 'WC_Geolite_Integration', false ) ) {
  267. require_once WC_ABSPATH . 'includes/class-wc-geolite-integration.php';
  268. }
  269. $geolite = new WC_Geolite_Integration( $database );
  270. return $geolite->get_country_iso( $ip_address );
  271. }
  272. /**
  273. * Use APIs to Geolocate the user.
  274. *
  275. * Geolocation APIs can be added through the use of the woocommerce_geolocation_geoip_apis filter.
  276. * Provide a name=>value pair for service-slug=>endpoint.
  277. *
  278. * If APIs are defined, one will be chosen at random to fulfil the request. After completing, the result
  279. * will be cached in a transient.
  280. *
  281. * @param string $ip_address IP address.
  282. * @return string
  283. */
  284. private static function geolocate_via_api( $ip_address ) {
  285. $country_code = get_transient( 'geoip_' . $ip_address );
  286. if ( false === $country_code ) {
  287. $geoip_services = apply_filters( 'woocommerce_geolocation_geoip_apis', self::$geoip_apis );
  288. if ( empty( $geoip_services ) ) {
  289. return '';
  290. }
  291. $geoip_services_keys = array_keys( $geoip_services );
  292. shuffle( $geoip_services_keys );
  293. foreach ( $geoip_services_keys as $service_name ) {
  294. $service_endpoint = $geoip_services[ $service_name ];
  295. $response = wp_safe_remote_get( sprintf( $service_endpoint, $ip_address ), array( 'timeout' => 2 ) );
  296. if ( ! is_wp_error( $response ) && $response['body'] ) {
  297. switch ( $service_name ) {
  298. case 'ipinfo.io':
  299. $data = json_decode( $response['body'] );
  300. $country_code = isset( $data->country ) ? $data->country : '';
  301. break;
  302. case 'ip-api.com':
  303. $data = json_decode( $response['body'] );
  304. $country_code = isset( $data->countryCode ) ? $data->countryCode : ''; // @codingStandardsIgnoreLine
  305. break;
  306. default:
  307. $country_code = apply_filters( 'woocommerce_geolocation_geoip_response_' . $service_name, '', $response['body'] );
  308. break;
  309. }
  310. $country_code = sanitize_text_field( strtoupper( $country_code ) );
  311. if ( $country_code ) {
  312. break;
  313. }
  314. }
  315. }
  316. set_transient( 'geoip_' . $ip_address, $country_code, WEEK_IN_SECONDS );
  317. }
  318. return $country_code;
  319. }
  320. }
  321. WC_Geolocation::init();