You are here

function _geoip_seek_country in GeoIP API 6

Same name and namespace in other branches
  1. 7 lib/geoip.inc \_geoip_seek_country()
4 calls to _geoip_seek_country()
geoip_country_id_by_addr in lib/geoip.inc
_get_org in lib/geoip.inc
_get_record in lib/geoipcity.inc
_get_region in lib/geoip.inc

File

lib/geoip.inc, line 419

Code

function _geoip_seek_country($gi, $ipnum) {
  $offset = 0;
  for ($depth = 31; $depth >= 0; --$depth) {
    if ($gi->flags & GEOIP_MEMORY_CACHE) {

      // workaround php's broken substr, strpos, etc handling with
      // mbstring.func_overload and mbstring.internal_encoding
      $enc = mb_internal_encoding();
      mb_internal_encoding('ISO-8859-1');
      $buf = substr($gi->memory_buffer, 2 * $gi->record_length * $offset, 2 * $gi->record_length);
      mb_internal_encoding($enc);
    }
    elseif ($gi->flags & GEOIP_SHARED_MEMORY) {
      $buf = @shmop_read($gi->shmid, 2 * $gi->record_length * $offset, 2 * $gi->record_length);
    }
    else {
      fseek($gi->filehandle, 2 * $gi->record_length * $offset, SEEK_SET) == 0 or die("fseek failed");
      $buf = fread($gi->filehandle, 2 * $gi->record_length);
    }
    $x = array(
      0,
      0,
    );
    for ($i = 0; $i < 2; ++$i) {
      for ($j = 0; $j < $gi->record_length; ++$j) {
        $x[$i] += ord($buf[$gi->record_length * $i + $j]) << $j * 8;
      }
    }
    if ($ipnum & 1 << $depth) {
      if ($x[1] >= $gi->databaseSegments) {
        return $x[1];
      }
      $offset = $x[1];
    }
    else {
      if ($x[0] >= $gi->databaseSegments) {
        return $x[0];
      }
      $offset = $x[0];
    }
  }
  trigger_error("error traversing database - perhaps it is corrupt?", E_USER_ERROR);
  return false;
}