function get_geodata($ip) { require _TRACK_LIB_PATH . "/maxmind/geoipregionvars.php"; // названия регионов if (defined('_PHP5_GEOIP_ENABLED') && _PHP5_GEOIP_ENABLED || function_exists('geoip_record_by_name')) { $geoinfo = geoip_record_by_name($ip); $ispname = geoip_isp_by_name($ip); $cur_city = $geoinfo['city']; $cur_region = $geoinfo['region']; $cur_country = $geoinfo['country_code']; } else { require _TRACK_LIB_PATH . "/maxmind/geoip.inc.php"; require _TRACK_LIB_PATH . "/maxmind/geoipcity.inc.php"; $gi = geoip_open(_TRACK_STATIC_PATH . "/maxmind/MaxmindCity.dat", GEOIP_STANDARD); $record = geoip_record_by_addr($gi, $ip); $ispname = geoip_org_by_addr($gi, $ip); geoip_close($gi); $cur_city = $record->city; $cur_region = $record->region; $cur_country = $record->country_code; // Resolve GeoIP extension conflict if (function_exists('geoip_country_code_by_name') && $cur_country == '') { $cur_country = geoip_country_code_by_name($ip); } } return array('country' => $cur_country, 'region' => $cur_region, 'state' => $GEOIP_REGION_NAME[$cur_country][$cur_region], 'city' => $cur_city, 'isp' => $ispname); }
public function getMyTimezone() { //return @geoip_time_zone_by_country_and_region ( geoip_country_code_by_name('85.12.204.141')); $session = JFactory::getSession(); $cart = $session->get('cart'); $item = new stdClass(); if (isset($cart['my_timezone']) && $cart['my_timezone']) { $item->my_timezone = $cart['my_timezone']; } else { if ($_SERVER['HTTP_HOST'] == 'cloudinterpreter.tst') { $item->my_timezone = 'Europe/Moscow'; } else { $item->my_timezone = @geoip_time_zone_by_country_and_region(geoip_country_code_by_name($_SERVER['REMOTE_ADDR'])); } } if (isset($cart['my_partner_timezone']) && $cart['my_partner_timezone']) { $item->my_partner_timezone = $cart['my_partner_timezone']; } else { if ($_SERVER['HTTP_HOST'] == 'cloudinterpreter.tst') { $item->my_partner_timezone = 'Europe/Moscow'; } else { $item->my_partner_timezone = @geoip_time_zone_by_country_and_region(geoip_country_code_by_name($_SERVER['REMOTE_ADDR'])); } } if (!$item->my_timezone) { $item->my_timezone = 'Europe/Moscow'; $item->my_partner_timezone = 'Europe/Moscow'; } return $item; }
public function blockCountryView(Result $result) { $result->getParam('request'); $allow = $this->preferences->get('foolfuuka.plugins.geoip_region_lock.allow_view'); $disallow = $this->preferences->get('foolfuuka.plugins.geoip_region_lock.disallow_view'); if ($allow || $disallow) { $country = strtolower(\geoip_country_code_by_name($request->getClientIp())); } if ($allow) { $allow = explode(',', $allow); foreach ($allow as $al) { if (strtolower(trim($al)) == $country) { return null; } } $result->set(new Response(_i('Not available in your country.'), 403)); return; } if ($disallow) { $disallow = explode(',', $disallow); foreach ($disallow as $disal) { if (strtolower(trim($disal)) == $country) { $result->set(new Response(_i('Not available in your country.'), 403)); throw new NotFoundHttpException(); } } } return null; }
function dmn_getcountry($mnip, &$countrycode) { $mnipalone = substr($mnip, 0, strpos($mnip, ":")); $res = geoip_country_name_by_name($mnipalone); $countrycode = strtolower(geoip_country_code_by_name($mnipalone)); return $res; }
public function isThirdPayOn() { $countryCode = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']); $log_array = array('type' => 'geoip country code_by name', 'msg' => $countryCode); log_message('gash', json_encode($log_array)); echo $countryCode; }
public function execute($sub) { global $wgOut, $wgRequest; global $wgLandingPageBase, $wgChapterLandingPages, $wgLandingPageDefaultTarget; $lang = preg_match('/^[A-Za-z-]+$/', $wgRequest->getVal('lang')) ? $wgRequest->getVal('lang') : 'en'; $utm_source = $wgRequest->getVal('utm_source'); $utm_medium = $wgRequest->getVal('utm_medium'); $utm_campaign = $wgRequest->getVal('utm_campaign'); $referrer = $wgRequest->getHeader('referer'); $target = $wgRequest->getVal('target', null); if (!$target) { $target = $wgLandingPageDefaultTarget; } $tracking = '?' . wfArrayToCGI(array('utm_source' => "{$utm_source}", 'utm_medium' => "{$utm_medium}", 'utm_campaign' => "{$utm_campaign}", 'referrer' => "{$referrer}", 'target' => "{$target}")); $ip = $wgRequest->getVal('ip') ? $wgRequest->getVal('ip') : wfGetIP(); if (IP::isValid($ip)) { $country = geoip_country_code_by_name($ip); if (is_string($country) && array_key_exists($country, $wgChapterLandingPages)) { $wgOut->redirect($this->getDestination($utm_source) . '/' . $wgChapterLandingPages[$country] . $tracking); return; } } // No valid IP or chapter page - let's just go for the passed in url or our fallback if (Http::isValidURI($target)) { $wgOut->redirect($target . '/' . $lang . $tracking); return; } else { $wgOut->redirect($wgLandingPageBase . $target . '/' . $lang . $tracking); } }
static function getIPCountry($ip) { if (function_exists('geoip_db_avail') && geoip_db_avail(GEOIP_COUNTRY_EDITION)) { try { try { return geoip_country_code_by_name($ip); } catch (Exception $e) { } } catch (ErrorException $e) { } } try { $country = json_decode(file_get_contents('https://freegeoip.net/json/' . $ip)); if (isset($country) && isset($country->country_code) && $country->country_code != '') { return $country->country_code; } } catch (Exception $e) { } try { $country = json_decode(file_get_contents('http://ip-api.com/json/' . $ip)); if (isset($country) && isset($country->countryCode) && $country->countryCode != '') { return $country->countryCode; } } catch (Exception $e) { } try { $country = trim(file_get_contents("http://api.hostip.info/country.php?ip=" . $ip)); if ($country != 'XX') { return $country; } } catch (Exception $e) { } return 'XX'; }
/** * Get the country by IP * Return an array with : short name, like 'us', long name, like 'United States and response like 'OK' or <error_message> ' * @access public * @param string $ip * @return array */ public function getCountryByIp($ip) { $country = array(0 => 'unknown', 1 => 'NA', 'response' => 'OK'); if (Dot_Kernel::validIp($ip) != "public") { return $country; } if (extension_loaded('geoip') == false) { // GeoIp extension is not active $api = new Dot_Geoip_Country(); $geoipPath = $this->config->resources->geoip->path; if (file_exists($geoipPath)) { $country = $api->getCountryByAddr($geoipPath, $ip); } else { $country['response'] = 'Warning: ' . $this->option->warningMessage->modGeoIp; } } if (function_exists('geoip_db_avail') && geoip_db_avail(GEOIP_COUNTRY_EDITION) && 'unknown' == $country[0]) { //if GeoIP.dat file exists $countryCode = geoip_country_code_by_name($ip); $countryName = geoip_country_name_by_name($ip); $country[0] = $countryCode != false ? $countryCode : 'unknown'; $country[1] = $countryName != false ? $countryName : 'NA'; } if ('unknown' == $country[0]) { // GeoIp extension is active, but .dat files are missing $api = new Dot_Geoip_Country(); $geoipPath = $this->config->resources->geoip->path; if (file_exists($geoipPath)) { $country = $api->getCountryByAddr($geoipPath, $ip); } else { $country['response'] = 'Warning: ' . $this->option->warningMessage->modGeoIp; } } return $country; }
function execute($par) { global $wgRequest, $wgOut, $wgFundraiserLPDefaults; // Set the country parameter $country = $wgRequest->getVal('country'); // If no country was passed do a GeoIP lookup if (!$country) { if (function_exists('geoip_country_code_by_name')) { $ip = wfGetIP(); if (IP::isValid($ip)) { $country = geoip_country_code_by_name($ip); } } } // If country still isn't set, set it to the default if (!$country) { $country = $wgFundraiserLPDefaults['country']; } $params = array('country' => $country); // Pass any other params that are set $excludeKeys = array('country', 'title'); foreach ($wgRequest->getValues() as $key => $value) { // Skip the required variables if (!in_array($key, $excludeKeys)) { $params[$key] = $value; } } // Redirect to FundraiserLandingPage $wgOut->redirect($this->getTitleFor('FundraiserLandingPage')->getLocalUrl($params)); }
public function onPreLogin(PlayerPreLoginEvent $event) { $p = $event->getPlayer(); $i = $p->getAddress(); $co = geoip_country_code_by_name($i); if ($this->c[$co]) { $p->close("", $this->reason[$co]); $event->setCancelled(true); } }
public function getCountry($visitorAddress) { if (!function_exists("geoip_country_code_by_name")) { // @codeCoverageIgnoreStart throw new \InvalidArgumentException("It seems, the geo-ip extension is not installed for php."); // @codeCoverageIgnoreEnd } $counrtyCode = @\geoip_country_code_by_name($visitorAddress); return $counrtyCode; }
function login_admin() { $login_success = null; if (isset($_POST['login'])) { $login = $_POST['login']; $this->form_validation->set_rules('login[member_code]', 'Email / Member ID', 'required'); $this->form_validation->set_rules('login[password]', 'required'); if ($this->form_validation->run() == FALSE) { $login_success = false; $this->nativesession->set_flashdata('login_status', '<div class="alert alert-danger">' . validation_errors() . '</div>'); $this->index(); } else { // $data = array('member_code' => $login[ 'member_code' ]); $potential_user = $this->admin_login_model->get_user_existing_data($login['member_code']); if ($potential_user) { $this->load->library('PBKDF2'); $admin = $potential_user; $pbkdf2 = new PBKDF2(); if ($pbkdf2->validatePassword($login['password'], $admin['password'])) { if ($admin['status'] == 'active') { $login_success = true; if (isset($login['remember_me'])) { // @TODO remember me mechanism } $this->nativesession->set(array('is_logged_in' => true, 'is_gan_admin_logged_in' => true, 'member_id' => $admin['id'], 'member_code' => $admin['member_code'], 'account_type' => $admin['account_type'])); // $country_code = function_exists( 'geoip_country_code_by_name' ) ? geoip_country_code_by_name( $_SERVER[ 'REMOTE_ADDR' ] ) : ''; $member_id = (string) $admin['id']; $member_data = array('last_login_date' => date('Y-m-d H:i:s'), 'last_login_ip' => $_SERVER['REMOTE_ADDR'], 'last_login_country' => function_exists('geoip_country_code_by_name') ? geoip_country_code_by_name($_SERVER['REMOTE_ADDR']) : ''); $this->admin_login_model->update_member($member_id, $member_data); redirect(base_url('admin/home')); } else { if ($member['status'] == 'inactive') { $this->nativesession->set_flashdata('login_status', '<div class="alert alert-danger">It seems that your account is inactive. please contact your administrator.</div>'); $login_success = false; redirect(base_url('login')); } else { $this->nativesession->set_flashdata('login_status', '<div class="alert alert-danger">Your account is suspended, please contact administrator.</div>'); $login_success = false; redirect(base_url('admin/login')); } } } else { $this->nativesession->set_flashdata('login_status', '<div class="alert alert-danger">Incorrect Email/member id or password ' . $potential_user . '.</div>'); $login_success = false; redirect(base_url('admin/login')); } } else { $this->nativesession->set_flashdata('login_status', '<div class="alert alert-danger">Incorrect Member ID or Password : Acces Denied.</div>'); $login_success = false; redirect(base_url('admin/login')); } } } }
public function checkGeo() { $targetGeo = json_decode($this->target_geo); if ($targetGeo) { $clientCountry = strtolower(geoip_country_code_by_name(getClientIp())); if (in_array($clientCountry, $targetGeo)) { return true; } } return false; }
public function getCountryCode() { if (empty($this->countryCode) && !YII_DEBUG) { if (empty(Yii::app()->request->cookies['country_code'])) { $this->countryCode = geoip_country_code_by_name($this->getUserHostAddress()); Yii::app()->request->cookies['country_code'] = new CHttpCookie('country_code', $this->countryCode, array('expire' => time() + 86400)); } else { $this->countryCode = Yii::app()->request->cookies['country_code']; } } return $this->countryCode; }
/** * Uses the GeoIP PECL module to get a visitor's location based on their IP address. * * This function will return different results based on the data available. If a city * database can be detected by the PECL module, it may return the country code, * region code, city name, area code, latitude, longitude and postal code of the visitor. * * Alternatively, if only the country database can be detected, only the country code * will be returned. * * The GeoIP PECL module will detect the following filenames: * - GeoIP.dat * - GeoIPCity.dat * - GeoIPISP.dat * - GeoIPOrg.dat * * Note how GeoLiteCity.dat, the name for the GeoLite city database, is not detected * by the PECL module. * * @param array $info Must have an 'ip' field. * @return array */ public function getLocation($info) { $ip = $this->getIpFromInfo($info); $result = array(); // get location data if (self::isCityDatabaseAvailable()) { // Must hide errors because missing IPV6: $location = @geoip_record_by_name($ip); if (!empty($location)) { $result[self::COUNTRY_CODE_KEY] = $location['country_code']; $result[self::REGION_CODE_KEY] = $location['region']; if ($location['region'] == "18" && $location['city'] == "Milan") { $result[self::REGION_CODE_KEY] = "09"; } $result[self::CITY_NAME_KEY] = utf8_encode($location['city']); $result[self::AREA_CODE_KEY] = $location['area_code']; $result[self::LATITUDE_KEY] = $location['latitude']; $result[self::LONGITUDE_KEY] = $location['longitude']; $result[self::POSTAL_CODE_KEY] = $location['postal_code']; } } else { if (self::isRegionDatabaseAvailable()) { $location = @geoip_region_by_name($ip); if (!empty($location)) { $result[self::REGION_CODE_KEY] = $location['region']; $result[self::COUNTRY_CODE_KEY] = $location['country_code']; } } else { $result[self::COUNTRY_CODE_KEY] = @geoip_country_code_by_name($ip); } } // get organization data if the org database is available if (self::isOrgDatabaseAvailable()) { $org = @geoip_org_by_name($ip); if ($org !== false) { $result[self::ORG_KEY] = utf8_encode($org); } } // get isp data if the isp database is available if (self::isISPDatabaseAvailable()) { $isp = @geoip_isp_by_name($ip); if ($isp !== false) { $result[self::ISP_KEY] = utf8_encode($isp); } } if (empty($result)) { return false; } $this->completeLocationResult($result); return $result; }
function checkIp_joyspade() { $countryarray = array('TW', 'SG', 'MY', 'TH', 'ID', 'PH', 'BN', 'KH', 'LA', 'MM', 'VN', 'TL'); //东南亚+台湾 $countryCode = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']); //"1.0.16.0" $_SERVER['REMOTE_ADDR'] foreach ($countryarray as $country) { if ($countryCode == $country) { return; } } echo "<html>\n <head><title>404 Not Found</title></head>\n <body bgcolor=\"white\">\n <center><h1>404 Not Found</h1></center>\n <hr><center>nginx/1.6.0</center>\n </body>\n </html>\n "; die; }
function get_geodata($ip) { require_once _TRACK_LIB_PATH . "/maxmind/geoip.inc.php"; require_once _TRACK_LIB_PATH . "/maxmind/geoipcity.inc.php"; require_once _TRACK_LIB_PATH . "/maxmind/geoipregionvars.php"; $gi = geoip_open(_TRACK_STATIC_PATH . "/maxmind/MaxmindCity.dat", GEOIP_STANDARD); $record = geoip_record_by_addr($gi, $ip); $isp = geoip_org_by_addr($gi, $ip); geoip_close($gi); $cur_country = $record->country_code; // Resolve GeoIP extension conflict if (function_exists('geoip_country_code_by_name') && $cur_country == '') { $cur_country = geoip_country_code_by_name($ip); } return array('country' => $cur_country, 'state' => $GEOIP_REGION_NAME[$record->country_code][$record->region], 'city' => $record->city, 'region' => $record->region, 'isp' => $isp); }
function login_member() { $login_success = null; if (isset($_POST['login'])) { $login = $_POST['login']; $data = array('member_code' => $login['member_code']); $potential_user = $this->member_login_model->get_user_existing_data($data); if ($potential_user) { $this->load->library('PBKDF2'); $member = $potential_user; $pbkdf2 = new PBKDF2(); if ($pbkdf2->validatePassword($login['password'], $member['password'])) { if ($member['status'] != 'deactivated' && $member['status'] != 'inactive') { $login_success = true; if (isset($login['remember_me'])) { // @TODO remember me mechanism } $this->nativesession->set(array('is_logged_in' => true, 'is_member_logged_in' => true, 'member_id' => $member['id'], 'member_code' => $member['member_code'], 'ms_status' => $member['status'])); // $country_code = function_exists( 'geoip_country_code_by_name' ) ? geoip_country_code_by_name( $_SERVER[ 'REMOTE_ADDR' ] ) : ''; $member_id = (string) $member['id']; $member_data = array('last_login_date' => date('Y-m-d H:i:s'), 'last_login_ip' => $_SERVER['REMOTE_ADDR'], 'last_login_country' => function_exists('geoip_country_code_by_name') ? geoip_country_code_by_name($_SERVER['REMOTE_ADDR']) : ''); $this->member_login_model->update_member($member_id, $member_data); redirect(base_url('members/home')); } else { if ($member['status'] == 'inactive') { $this->nativesession->set_flashdata('login_status', '<div class="alert alert-danger">It seems that your account is inactive. please contact your administrator.</div>'); $login_success = false; redirect(base_url('login')); } else { $this->nativesession->set_flashdata('login_status', '<div class="alert alert-danger">Your account is suspended, please contact administrator.</div>'); $login_success = false; redirect(base_url('login')); } } } else { $this->nativesession->set_flashdata('login_status', '<div class="alert alert-danger">Incorrect Member ID or Password.</div>'); $login_success = false; redirect(base_url('login')); } } else { $this->nativesession->set_flashdata('login_status', '<div class="alert alert-danger">Incorrect Member ID or Password.</div>'); $login_success = false; redirect(base_url('login')); } } }
function _check_ip($ip, $ignore_ips = '', $check_type = 'force') { $masks = ['0.0.0.0/8', '10.0.0.0/8', '127.0.0.0/8', '128.0.0.0/16', '169.254.0.0/16', '172.16.0.0/12', '191.255.0.0/16', '192.0.0.0/24', '192.0.2.0/24', '192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '223.255.255.0/24', '224.0.0.0/4', '240.0.0.0/4', '255.255.255.255/']; $ip = preg_replace('/[^\\d\\.]/', ',', $ip); $ips = explode(',', $ip); foreach ((array) $ips as $item) { if (empty($item) || !empty($ignore_ips) && isset($ignore_ips[$item])) { continue; } $flag = false; preg_match('/([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})/', $item, $cur_ip); $ip = isset($cur_ip[1]) ? $cur_ip[1] : false; if (!$ip) { continue; } $flag = true; foreach ((array) $masks as $mask) { list($net_addr, $net_mask) = explode('/', $mask); if ($net_mask <= 0) { continue; } if (empty($net_mask) && $item == $net_addr) { $flag = false; break; } $ip_binary_string = sprintf('%032b', ip2long($item)); $net_binary_string = sprintf('%032b', ip2long($net_addr)); if (substr_compare($ip_binary_string, $net_binary_string, 0, $net_mask) === 0) { $flag = false; } } if ($flag) { if (function_exists('geoip_country_code_by_name') && strtoupper($check_type) == 'GEO') { $test = @geoip_country_code_by_name($ip); if ($test) { return trim($ip); } } else { return trim($ip); } } } return false; }
/** * Determines if the given request matches the criteria. * * @param array|string $criteria List of criteria, format: [] with keys rule * and data; may be serialized * @param boolean $matchOnEmpty If true and there's no criteria, true is * returned; otherwise, false * @param Zend_Controller_Request_Http $request Request to check against * * @return boolean */ public static function requestMatchesCriteria($criteria, $matchOnEmpty = false, Zend_Controller_Request_Http $request = null) { if (!($criteria = XenForo_Helper_Criteria::unserializeCriteria($criteria))) { return (bool) $matchOnEmpty; } if (!$request) { $request = new Zend_Controller_Request_Http(); } foreach ($criteria as $criterion) { $data = $criterion['data']; switch ($criterion['rule']) { // contains at least x links case 'geoip_country': if (!isset($data['countries'])) { return false; } if (!function_exists('geoip_country_code_by_name')) { return false; } try { $country = geoip_country_code_by_name($request->getClientIp(true)); } catch (Exception $e) { return false; } if (!in_array($country, $data['countries'])) { return false; } break; // user has open port // user has open port case 'open_port': if (empty($data['port'])) { return false; } if (@fsockopen($_SERVER['REMOTE_ADDR'], $data['port'], $errstr, $errno, 1)) { return false; } break; } } return true; }
/** * look up ip and return 2-char country code * * @param string $ip optional, if empty will use iputility to obtain ip * @return array 'de' or '--' if unshure * @throws ErrorException */ function lookup($ip = '') { if (empty($ip)) { $ipUtil = getUtil('Ip'); $ip = $ipUtil->getIp(); } if (function_exists('geoip_country_code_by_name')) { $temp = geoip_country_code_by_name($ip); if (!empty($temp)) { return $temp; } return '--'; } if (is_file($this->cmdLine)) { $ret = shell_exec($this->cmdLine . ' ' . $ip); if (!empty($ret)) { foreach ($ret as $line) { $temp = explode(':', $line); if (!empty($line[1])) { $parts = explode(',', $line); if (!empty($parts[0]) && '--' != $parts[0]) { return $parts[0]; } //if !-- } //!empty(line) } //foreach } //empty $ret } //file if (class_exists('Net_GeoIP')) { $inst = NetGeoIP::getInstance(); $temp = $inst->lookupCountryCode($ip); if (!empty($temp)) { return $temp; } return '--'; } throw new ErrorException('geoip: no extension, no binary, no pear-class/db, fatal error'); }
public static function country_code_by_addr($addr, $host) { // first run without geoip extension if (empty(self::$_gi) && !function_exists('geoip_country_code_by_name')) { require_once dirname(__FILE__) . "/../lib/geoip.inc"; self::$_gi = geoip_open(dirname(__FILE__) . "/../lib/geoip.dat", GEOIP_STANDARD); } // without geoip extension if (isset(self::$_gi) && function_exists('geoip_country_code_by_addr')) { $code = geoip_country_code_by_addr(self::$_gi, $addr); // with geoip extension } elseif (function_exists('geoip_country_code_by_name')) { $code = geoip_country_code_by_name($host); } if (empty($code) || $code == 'AP' || $code == 'A1' || $code == 'A2') { $code = 'numeric'; } $code = strtolower($code); return $code; }
public static function geoIP() { switch (APPLICATION_ENV) { case 'production': if (preg_match('@127\\.*@', _IP or preg_match('@10\\.*@', _IP) or preg_match('@172\\.*@', _IP)) or preg_match('@192\\.168\\.*@', _IP) or _IP == '127.0.0.1') { $result = 'LO'; } else { $result = geoip_country_code_by_name(_IP); } break; case 'development': $countries = array('74.125.43.103', '86.134.153.24', '86.122.153.245'); $result = geoip_country_code_by_name($countries[array_rand($countries)]); break; case 'testing': $countries = array('US', 'CN', 'RU', 'RO', 'GN'); $result = $countries[array_rand($countries)]; break; } return $result; }
/** * Method checks country code by native php function or search in db file if native function doesn't exist * @author Dmitry Fedorov <*****@*****.**> * @version 1.0.2 on 2015-08-05 * @return string|null */ public static function getCountryCode() { $country = null; if (function_exists('geoip_country_code_by_name')) { // trick for local using (@author Constantine <*****@*****.**>) $userIp = \Yii::$app->getRequest()->getUserIP(); if ($userIp == '127.0.0.1' || $userIp == '::1') { $userIp = self::DEFAULT_USER_IP; } $country = geoip_country_code_by_name($userIp); } else { $geoReader = new Reader(\Yii::getAlias('@geolocation/data/GeoLite2-Country.mmdb')); try { $country = $geoReader->country(\Yii::$app->getRequest()->getUserIP()); $country = $country->country->isoCode; } catch (AddressNotFoundException $e) { \Yii::getLogger()->log($e->getMessage(), Logger::LEVEL_WARNING); } } return $country; }
/** * {@inheritDoc} */ public function getGeocodedData($address) { if (!filter_var($address, FILTER_VALIDATE_IP)) { throw new UnsupportedException('The GeoipProvider does not support Street addresses.'); } // This API does not support IPv6 if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { throw new UnsupportedException('The GeoipProvider does not support IPv6 addresses.'); } if ('127.0.0.1' === $address) { return array($this->getLocalhostDefaults()); } $results = array('country_name' => @geoip_country_name_by_name($address), 'country_code' => @geoip_country_code_by_name($address)); if ($results['country_code'] === false) { throw new NoResultException(sprintf('Could not find %s ip address in database.', $address)); } $timezone = @geoip_time_zone_by_country_and_region($results['country_code']) ?: null; $results = array_merge($this->getDefaults(), array('country' => $results['country_name'], 'countryCode' => $results['country_code'], 'timezone' => $timezone)); return array(array_map(function ($value) { return is_string($value) ? utf8_encode($value) : $value; }, $results)); }
/** * Returns country-code of request IP-geolocation * * @return string|null */ public static function getGeoIpCountryCode() { // Try Apache mod_geoip method: if (isset($_SERVER['GEOIP_COUNTRY_CODE']) && is_string($_SERVER['GEOIP_COUNTRY_CODE'])) { return $_SERVER['GEOIP_COUNTRY_CODE']; } // Try PHP (php5-geoip package) method: if (is_callable('geoip_country_code_by_name')) { $ipList = self::getIParray(); try { $countryCode = @geoip_country_code_by_name($ipList[0]); } catch (\Exception $e) { $countryCode = false; } if (is_string($countryCode) && !in_array($countryCode, array('A1', 'A2', 'O1'))) { // See special countries list in: http://dev.maxmind.com/geoip/legacy/codes/iso3166/ return $countryCode; } } // Failed finding Geo-IP country: return null; }
/** * Init */ public function init() { /** * Define */ $time_zone_name = null; /* * Check user ip */ $ip = \Yii::$app->request->getUserIP(); /** * Exclude ip */ foreach ($this->changeByIp as $filter => $timezone) { if ($filter === $ip || ($pos = strpos($filter, '*')) !== false && !strncmp($ip, $filter, $pos)) { $time_zone_name = $timezone; break; } } /** * Find timezone */ if (!$time_zone_name) { try { $country = geoip_country_code_by_name($ip); $region = geoip_region_by_name($ip); $time_zone_name = geoip_time_zone_by_country_and_region($country, $region['region']); } catch (\Exception $e) { } if (!$time_zone_name) { $time_zone_name = $this->default; } } /** * Set timezone */ \Yii::$app->setTimeZone($time_zone_name); }
protected function _getCountryCodeFromIp($ip) { //GeoIP .dat file $file = $this->libpath . '/lib/Data/' . $this->_geoipHelper->getConfig('general/file_location'); try { if (file_exists($file)) { if (defined('GEOIP_LOCAL')) { $gi = geoip_open($file, GEOIP_STANDARD); $location = geoip_country_code_by_addr($gi, $ip); geoip_close($gi); return $location; } else { $this->_logger->addDebug(".dat file detected, but you haven't enabled the option to use it ('Use my own GeoIP file' in config)"); } } else { return geoip_country_code_by_name($ip); } } catch (Exception $e) { $this->_logger->addDebug("Warning: Could not find GeoIP Country Code. Please check your GeoIP data - Have you included a geoip.dat file?"); $this->_logger->addDebug($e->getMessage()); return $this->_scopeConfig->getValue('general/country/default', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); } }
public function execute($sub) { global $wgRequest, $wgPriorityCountries; // Pull in query string parameters $language = $wgRequest->getVal('language', 'en'); $this->basic = $wgRequest->getBool('basic'); $country = $wgRequest->getVal('country'); // If no country was passed, try to do GeoIP lookup // Requires php5-geoip package if (!$country && function_exists('geoip_country_code_by_name')) { $ip = wfGetIP(); if (IP::isValid($ip)) { $country = geoip_country_code_by_name($ip); } } if (!$country) { $country = 'US'; // Default } // determine if we are fulfilling a request for a priority country $priority = in_array($country, $wgPriorityCountries); // handle the actual redirect $this->routeRedirect($country, $language, $priority); }
/** * Handler for the BeforePageDisplay hook * * @param $out OutputPage * @param $text String * @return bool */ public function beforePageDisplayHTML(&$out, &$text) { global $wgRequest, $wgConf, $wgEnableZeroRatedMobileAccessTesting; wfProfileIn(__METHOD__); $DB = wfGetDB(DB_MASTER); $DBName = $DB->getDBname(); list($site, $lang) = $wgConf->siteFromDB($DBName); if ($site == 'wikipedia' || $wgEnableZeroRatedMobileAccessTesting) { $xDevice = isset($_SERVER['HTTP_X_DEVICE']) ? $_SERVER['HTTP_X_DEVICE'] : ''; self::$useFormat = $wgRequest->getText('useformat'); if (self::$useFormat !== 'mobile' && self::$useFormat !== 'mobile-wap' && !$xDevice) { wfProfileOut(__METHOD__); return true; } $output = ''; self::$renderZeroRatedLandingPage = $wgRequest->getFuzzyBool('renderZeroRatedLandingPage'); self::$renderZeroRatedBanner = $wgRequest->getFuzzyBool('renderZeroRatedBanner'); self::$renderZeroRatedRedirect = $wgRequest->getFuzzyBool('renderZeroRatedRedirect'); self::$forceClickToViewImages = $wgRequest->getFuzzyBool('forceClickToViewImages'); self::$acceptBilling = $wgRequest->getVal('acceptbilling'); self::$title = $out->getTitle(); $carrier = $wgRequest->getHeader('HTTP_X_CARRIER'); if ($carrier !== '(null)' && $carrier) { self::$renderZeroRatedBanner = true; } if (self::$title->getNamespace() == NS_FILE) { self::$isFilePage = true; } if (self::$acceptBilling === 'no') { $targetUrl = $wgRequest->getVal('returnto'); $out->redirect($targetUrl, '301'); $out->output(); } if (self::$acceptBilling === 'yes') { $targetUrl = $wgRequest->getVal('returnto'); if ($targetUrl) { $out->redirect($targetUrl, '301'); $out->output(); } } if (self::$isFilePage && self::$acceptBilling !== 'yes') { $acceptBillingYes = Html::rawElement('a', array('href' => $wgRequest->appendQuery('renderZeroRatedBanner=true&acceptbilling=yes')), wfMsg('zero-rated-mobile-access-banner-text-data-charges-yes')); $referrer = $wgRequest->getHeader('referer'); $acceptBillingNo = Html::rawElement('a', array('href' => $wgRequest->appendQuery('acceptbilling=no&returnto=' . urlencode($referrer))), wfMsg('zero-rated-mobile-access-banner-text-data-charges-no')); $bannerText = Html::rawElement('h3', array('id' => 'zero-rated-banner-text'), wfMsg('zero-rated-mobile-access-banner-text-data-charges', $acceptBillingYes, $acceptBillingNo)); $banner = Html::rawElement('div', array('style' => 'display:none;', 'id' => 'zero-rated-banner-red'), $bannerText); $output .= $banner; $out->clearHTML(); $out->setPageTitle(null); } elseif (self::$renderZeroRatedRedirect === true) { $returnto = $wgRequest->getVal('returnto'); $acceptBillingYes = Html::rawElement('a', array('href' => $wgRequest->appendQuery('renderZeroRatedBanner=true&acceptbilling=yes&returnto=' . urlencode($returnto))), wfMsg('zero-rated-mobile-access-banner-text-data-charges-yes')); $referrer = $wgRequest->getHeader('referer'); $acceptBillingNo = Html::rawElement('a', array('href' => $wgRequest->appendQuery('acceptbilling=no&returnto=' . urlencode($referrer))), wfMsg('zero-rated-mobile-access-banner-text-data-charges-no')); $bannerText = Html::rawElement('h3', array('id' => 'zero-rated-banner-text'), wfMsg('zero-rated-mobile-access-banner-text-data-charges', $acceptBillingYes, $acceptBillingNo)); $banner = Html::rawElement('div', array('style' => 'display:none;', 'id' => 'zero-rated-banner-red'), $bannerText); $output .= $banner; $out->clearHTML(); $out->setPageTitle(null); } elseif (self::$renderZeroRatedBanner === true) { self::$carrier = $this->lookupCarrier($carrier); if (isset(self::$carrier['name'])) { $html = $out->getHTML(); $parsedHtml = $this->parseLinksForZeroQueryString($html); $out->clearHTML(); $out->addHTML($parsedHtml); $carrierLink = isset(self::$carrier['link']) ? self::$carrier['link'] : ''; $bannerText = Html::rawElement('span', array('id' => 'zero-rated-banner-text'), wfMsg('zero-rated-mobile-access-banner-text', $carrierLink)); $banner = Html::rawElement('div', array('style' => 'display:none;', 'id' => 'zero-rated-banner'), $bannerText); $output .= $banner; } } if (self::$renderZeroRatedLandingPage === true) { $out->clearHTML(); $out->setPageTitle(null); $output .= wfMsg('zero-rated-mobile-access-desc'); $languageNames = Language::getLanguageNames(); $country = $wgRequest->getVal('country'); $ip = $wgRequest->getVal('ip', wfGetIP()); // Temporary hack to allow for testing on localhost $countryIps = array('GERMANY' => '80.237.226.75', 'MEXICO' => '187.184.240.247', 'THAILAND' => '180.180.150.104', 'FRANCE' => '90.6.70.28'); $ip = strpos($ip, '192.168.') === 0 ? $countryIps['THAILAND'] : $ip; if (IP::isValid($ip)) { // If no country was passed, try to do GeoIP lookup // Requires php5-geoip package if (!$country && function_exists('geoip_country_code_by_name')) { $country = geoip_country_code_by_name($ip); } self::addDebugOutput($country); } $languageOptions = $this->createLanguageOptionsFromWikiText(); // self::$displayDebugOutput = true; $languagesForCountry = isset($languageOptions[self::getFullCountryNameFromCode($country)]) ? $languageOptions[self::getFullCountryNameFromCode($country)] : null; self::addDebugOutput(self::getFullCountryNameFromCode($country)); self::addDebugOutput($languagesForCountry); self::writeDebugOutput(); if (is_array($languagesForCountry)) { $sizeOfLanguagesForCountry = sizeof($languagesForCountry); for ($i = 0; $i < $sizeOfLanguagesForCountry; $i++) { $languageName = $languageNames[$languagesForCountry[$i]['language']]; $languageCode = $languagesForCountry[$i]['language']; $output .= Html::element('hr'); $output .= Html::element('h3', array('id' => 'lang_' . $languageCode), $languageName); if ($i == 0) { $output .= self::getSearchFormHtml($languageCode); } else { $languageUrl = sprintf(self::$formatMobileUrl, $languageCode); $output .= Html::element('a', array('id' => 'lang_' . $languageCode, 'href' => $languageUrl), wfMessage('zero-rated-mobile-access-home-page-selection', $languageName)->inLanguage($languageCode)); $output .= Html::element('br'); } } } $output .= Html::element('hr'); $output .= wfMsg('zero-rated-mobile-access-home-page-selection-text'); $output .= Html::openElement('select', array('id' => 'languageselection', 'onchange' => 'javascript:window.location = this.options[this.selectedIndex].value;')); $output .= Html::element('option', array('value' => ''), wfMsg('zero-rated-mobile-access-language-selection')); foreach ($languageNames as $languageCode => $languageName) { $output .= Html::element('option', array('value' => sprintf(self::$formatMobileUrl, $languageCode)), $languageName); } $output .= Html::closeElement('select'); } if ($output) { $output = Html::openElement('div', array('id' => 'zero-landing-page')) . $output . Html::closeElement('div'); $out->addHTML($output); } } wfProfileOut(__METHOD__); return true; }