class-wc-geolite-integration.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /**
  3. * Wrapper for MaxMind GeoLite2 Reader
  4. *
  5. * This class provide an interface to handle geolocation and error handling.
  6. *
  7. * Requires PHP 5.4+.
  8. *
  9. * @package WooCommerce\Classes
  10. * @since 3.4.0
  11. */
  12. defined( 'ABSPATH' ) || exit;
  13. /**
  14. * Geolite integration class.
  15. */
  16. class WC_Geolite_Integration {
  17. /**
  18. * MaxMind GeoLite2 database path.
  19. *
  20. * @var string
  21. */
  22. private $database = '';
  23. /**
  24. * Logger instance.
  25. *
  26. * @var WC_Logger
  27. */
  28. private $log = null;
  29. /**
  30. * Constructor.
  31. *
  32. * @param string $database MaxMind GeoLite2 database path.
  33. */
  34. public function __construct( $database ) {
  35. $this->database = $database;
  36. if ( ! class_exists( 'MaxMind\\Db\\Reader', false ) ) {
  37. $this->require_geolite_library();
  38. }
  39. }
  40. /**
  41. * Get country 2-letters ISO by IP address.
  42. * Returns empty string when not able to find any ISO code.
  43. *
  44. * @param string $ip_address User IP address.
  45. * @return string
  46. */
  47. public function get_country_iso( $ip_address ) {
  48. $iso_code = '';
  49. try {
  50. $reader = new MaxMind\Db\Reader( $this->database ); // phpcs:ignore PHPCompatibility.PHP.NewLanguageConstructs.t_ns_separatorFound
  51. $data = $reader->get( $ip_address );
  52. if ( isset( $data['country']['iso_code'] ) ) {
  53. $iso_code = $data['country']['iso_code'];
  54. }
  55. $reader->close();
  56. } catch ( Exception $e ) {
  57. $this->log( $e->getMessage(), 'warning' );
  58. }
  59. return sanitize_text_field( strtoupper( $iso_code ) );
  60. }
  61. /**
  62. * Logging method.
  63. *
  64. * @param string $message Log message.
  65. * @param string $level Log level.
  66. * Available options: 'emergency', 'alert',
  67. * 'critical', 'error', 'warning', 'notice',
  68. * 'info' and 'debug'.
  69. * Defaults to 'info'.
  70. */
  71. private function log( $message, $level = 'info' ) {
  72. if ( is_null( $this->log ) ) {
  73. $this->log = wc_get_logger();
  74. }
  75. $this->log->log( $level, $message, array( 'source' => 'geoip' ) );
  76. }
  77. /**
  78. * Require geolite library.
  79. */
  80. private function require_geolite_library() {
  81. require_once WC_ABSPATH . 'includes/libraries/geolite2/Reader/Decoder.php';
  82. require_once WC_ABSPATH . 'includes/libraries/geolite2/Reader/InvalidDatabaseException.php';
  83. require_once WC_ABSPATH . 'includes/libraries/geolite2/Reader/Metadata.php';
  84. require_once WC_ABSPATH . 'includes/libraries/geolite2/Reader/Util.php';
  85. require_once WC_ABSPATH . 'includes/libraries/geolite2/Reader.php';
  86. }
  87. }