select() ->from(Qs_Db::getTableName('Ip2Country'), array('code')) ->where('longFrom <= ?', $long, Zend_Db::BIGINT_TYPE) ->where('longTo >= ?', $long, Zend_Db::BIGINT_TYPE); $country = $db->fetchOne($select); } if (!$country) { if (false === ($country = Qs_GeoIpCountryWhois::_getWhoisCountryCodeFromCache($ip))) { $country = Qs_GeoIpCountryWhois::_getWhoisCountry($ip); } } return ($country) ? $country : $default; } /** * Get country code from cached data * * @param string $ip IP address * @return mixed If country found then return country code, else false */ protected static function _getWhoisCountryCodeFromCache($ip) { $db = Qs_Db::getInstance(); $select = $db->select() ->from(Qs_Db::getTableName('WhoisCache'), array('countryCode')) ->where('ip = ?', $ip); $country = $db->fetchOne($select); if ($country) { return $country; } return false; } /** * Save contry code to cache * * @param string $ip IP address * @param string $code Country code * @return Qs_GeoIpCountryWhois */ protected static function _saveWhoisCountryCode2Cache($ip, $code) { $db = Qs_Db::getInstance(); $data = array( 'ip' => $ip, 'countryCode' => $code ); $tableWhoisCache = new Qs_Db_Table(array('name' => Qs_Db::getTableName('WhoisCache'), 'db' => $db)); $tableWhoisCache->insert($data); } /** * Get country from whois (use whois linux command) * * @param string $ip IP address * @return string Country code */ protected static function _getWhoisCountry($ip) { $country = null; $output = array(); exec('whois ' . escapeshellarg($ip) . ' | grep -i \'Country:\'', $output); if (!empty($output)) { list(,$country) = explode(':', $output[0]); $country = trim($country); } if ($country) { Qs_GeoIpCountryWhois::_saveWhoisCountryCode2Cache($ip, $country); } return $country; } }