working on it ...

Filters

Explore Public Snippets

Sort by

Found 133 snippets matching: geoip

    public by simonwalker  1103  0  6  0

    Magento GeoIP Store Switcher Extension | FME

    Magento GeoIP Store Switcher by FME is a geo-targeting extension which detects the visitor’s real-time location and redirects them to a region customized store view. Using this Magento GeoIP store switcher extension, you can create multiple store views, customize their theme, and display relevant products on the front. Allow the visitors to manuall
    // https://www.fmeextensions.com/magento-geo-ip-default-store-view.html        

    public by AbhishekGhosh  339  3  3  0

    GEO IP TEST PHP Script

    GEO IP TEST PHP Script: geoip.php
    <html>
    <body>
    <?php
    
    $geoip_country_code = getenv(GEOIP_COUNTRY_CODE);
    $geoip_country_name = getenv(GEOIP_COUNTRY_NAME);
    $geoip_region = getenv(GEOIP_REGION);
    $geoip_city = getenv(GEOIP_CITY);
    $geoip_postal_code = getenv(GEOIP_POSTAL_CODE);
    $geoip_latitude = getenv(GEOIP_LATITUDE);
    $geoip_longitude = getenv(GEOIP_LONGITUDE);
    
    
    echo 'Country code: '.$geoip_country_code.'<br>';
    echo 'Country name: '.$geoip_country_name.'<br>';
    echo 'Region: '.$geoip_region.'<br>';
    echo 'City: '.$geoip_city.'<br>';
    echo 'Postal code: '.$geoip_postal_code.'<br>';
    echo 'Latitude: '.$geoip_latitude.'<br>';
    echo 'Longitude: '.$geoip_longitude.'<br>';
    
    ?>
    </body>
    </html>
    
    

    external by nickdavis  336  1  3  0

    Correction of WP Engine GeoIP example code on http://wpengine.com/support/geoip-personalizing-content-based-geography/ (taken from the geoip.php file of the plugin itself)

    Correction of WP Engine GeoIP example code on http://wpengine.com/support/geoip-personalizing-content-based-geography/ (taken from the geoip.php file of the plugin itself): geoip.php
    <?php
    
    function geoip_append_content( $content ) {
    	$geo = WPEngine\GeoIp::instance();
    	$content .= "How's the weather in {$geo->city()}, {$geo->region()} {$geo->country()}?<br /><br />";
    	return $content;
    }
    add_filter( 'the_content', 'geoip_append_content' );
    
    

    external by Hirokazu YOSHIDA  57  0  1  0

    geoip and geoip-c benchmark

    geoip and geoip-c benchmark: geoip_bench.rb
    require 'geoip'
    require 'benchmark'
    
    n = 1000000
    
    # geoip-c C extended library
    Benchmark.bm do |x|
      geoip = GeoIP::City.new("/usr/share/GeoIP/GeoLiteCity.dat", :memory, false)
      x.report { n.times { geoip.look_up("144.206.125.148") } }
      #       user     system      total        real
      # 10.480000   0.070000  10.550000 ( 10.604084)
    end
    
    
    # geoip pure Ruby implement
    Benchmark.bm do |x|
      geoip = GeoIP.new("/usr/share/GeoIP/GeoLiteCity.dat")
      x.report { n.times { geoip.city("144.206.125.148") } }
      #      user     system      total        real
      # 104.030000  25.760000 129.790000 (132.106001)
    end
    
    
    

    external by Syed Irfaq R.  161  0  2  0

    GeoIP Target Filter - Redirect targeted users to a specific URL, otherwise do nothing. - https://github.com/irazasyed/geoip-target-filter

    GeoIP Target Filter - Redirect targeted users to a specific URL, otherwise do nothing. - https://github.com/irazasyed/geoip-target-filter: geoip-target-filter.html
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Redirecting...</title>
      <script>
        /*!
         * GeoIP Target Filter
         * Copyright (c) 2014-16 Syed I.R
         * Licensed under the MIT.
         * Project: https://github.com/irazasyed/geoip-target-filter
         *
         * ---------------------------------------------------------------------
         * A small snippet for geo-filter redirection using GeoIP API.
         * Add your targeted country's "ISO 3166-1 - Alpha-2" codes to the filter
         * to automatically redirect targeted visitors to your targeted URL.
         *
         * Country Codes can be found @( Wikipedia - http://bit.ly/nWBMYz )
         * See Column: "Alpha-2 Code"
         * ---------------------------------------------------------------------
         */
        var filter              = ['US', 'GB', 'CA', 'AU', 'IN'];
        var targetVisitorsUrl   = 'http://domain.tld/';
        // ------------------------------------------------------
        // DON'T EDIT THE BELOW CODE UNLESS REQUIRED
        // ------------------------------------------------------
        /**
         * Check if the visitor is from targeted country, Redirect to target URL.
         * Otherwise do nothing.
         */
        function geoip(g){if(inArray(g.country_code,filter))window.top.location.href=targetVisitorsUrl}
        function inArray(r,n){for(var t=n.length,e=0;t>e;e++)if(n[e]==r)return!0;return!1}
        (function(g,e,o,i,p){i=g.createElement(e),p=g.getElementsByTagName(e)[0];i.async=0;i.src=o;p.parentNode.insertBefore(i,p)})(document,'script','https://freegeoip.net/json/?callback=geoip');
      </script>
    </head>
    <body>
        <p>Please wait...</p>
    </body>
    </html>
    
    

    external by Fedcomp  125  0  2  0

    PHP Psychostats GeoIP updater

    PHP Psychostats GeoIP updater: psychostats_geoip_updater.php
    #!/usr/bin/env php
    <?php
    /*
    	========== Psychostats GeoIP updater ==============
    	Автор: Fedcomp
    	Для работы необходимо php расширение для работы ZIP.
    	php_zip.dll для windows.
    	
    	Простой скрипт для обновления IP адресов стран в базе данных psychostats.
    */
    
    // Настройки. Настроено под мою локалку, изменяйте под себя.
    
    
    $mysql_host			= '127.0.0.1';	// Хост. Адрес mysql сервера
    $mysql_user			= 'mbot';		// Пользователь Mysql
    $mysql_pass			= 'mbot';		// Пароль Mysql
    $mysql_db			= 'mbot';		// Название базы данных с таблицами psychostats
    $mysql_tablename_ip	= 'ps_geoip_ip';// Название таблицы с GeoIP психостата
    $mysql_tablename_cc	= 'ps_geoip_cc';// Название таблицы с GeoIP психостата
    $download_link = 'http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip';	// Ссылка с которой скрипт загружает свежие записи
    
    // Количество списков с IP которые будут обрабатываться за один запрос.
    // Допустим 10 IP диапазонов за один запрос.
    // В 10 раз ускоряет выполнение скрипта. Значения больше 100 не рекомендуются
    define('PER_QUERY', 100);
    
    
    // == // Конец настроек =========
    
    /*
    array(6) {
      [0] =>
      string(7) "1.0.0.0"
      [1] =>
      string(9) "1.0.0.255"
      [2] =>
      string(8) "16777216"
      [3] =>
      string(8) "16777471"
      [4] =>
      string(2) "AU"
      [5] =>
      string(9) "Australia"
    }
    */
    define('CSV_IP_START',				2);
    define('CSV_IP_END',				3);
    define('CSV_COUNTRY_CODE_FIELD',	4);
    define('CSV_COUNTRY_NAME_FIELD',	5);
    
    
    // Подключаемся к базе
    if(!$db_link = @mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_db))
    	die('Ne mogu podlu4ica k mysql: '. mysqli_connect_error() . "\n");
    
    // Проверяем существует ли таблица со списокм айпи
    if (mysqli_num_rows(mysqli_query($db_link, "SHOW TABLES LIKE '{$mysql_tablename_ip}'")) == 0)
    	die('Tablica ne ukazana ili nazvanie neverno. $mysql_tablename_ip:' . $mysql_tablename_ip . "\n");
    
    // Проверяем существует ли таблица с названием стран
    if (mysqli_num_rows(mysqli_query($db_link, "SHOW TABLES LIKE '{$mysql_tablename_cc}'")) == 0)
    	die('Tablica ne ukazana ili nazvanie neverno. $mysql_tablename_cc:' . $mysql_tablename_cc . "\n");
    
    echo "Ska4ivaem bazu s novimi ip: {$download_link}\n";
    file_put_contents('db.zip', file_get_contents($download_link));
    echo "Otkrivaem zip archive\n";
    
    $z = new ZipArchive();
    if (!$z->open('db.zip')) die("archive povrejden.\n");
    if(!$fp = $z->getStream('GeoIPCountryWhois.csv')) die("archive povrejden.\n");
    
    $ips = array();
    $countries = array();
    while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
    	$countries[$data[CSV_COUNTRY_CODE_FIELD]] = $data[CSV_COUNTRY_NAME_FIELD];
    	$ips[] = array(
    		'cc'	=> $data[CSV_COUNTRY_CODE_FIELD],
    		'start'	=> $data[CSV_IP_START],
    		'end'	=> $data[CSV_IP_END],
    	);
    }
    fclose($fp);
    @unlink('db.zip');
    
    // Сначала удаляем старые записи с названиями стран
    mysqli_query($db_link, "TRUNCATE {$mysql_tablename_cc}");
    foreach($countries as $cc => $cn){
    	mysqli_query($db_link, "
    		INSERT INTO `{$mysql_tablename_cc}` (`cc`, `cn`)
    		VALUES ('" . mysqli_real_escape_string($db_link, $cc) . "', '" . mysqli_real_escape_string($db_link, $cn) . "');
    	");
    	echo "$cc => $cn\n";
    }
    
    // Сначала удаляем старые записи со списком айпи
    mysqli_query($db_link, "TRUNCATE {$mysql_tablename_ip}");
    for($i=0;$i<ceil(count($ips)/PER_QUERY);$i++){
    	$offset = $i*PER_QUERY;
    	$sql = "INSERT INTO `{$mysql_tablename_ip}` (`cc`, `start`, `end`)\nVALUES ";
    		// Foreach values
    		for($j=0;$j<PER_QUERY and count($ips)-$offset != $j;$j++) $sql .= '(' .
    			"'".mysqli_real_escape_string($db_link, $ips[$offset+$j]['cc'])."',"
    			. (int) $ips[$offset+$j]['start'] . ','
    			. (int) $ips[$offset+$j]['end'] .
    		"),\n";
    	$sql = substr($sql, 0, -2); // Вырезаем перевод строки и запятую;
    	mysqli_query($db_link, $sql);
    	echo "{$ips[$offset]['cc']} => {$ips[$offset]['start']}<{$ips[$offset]['end']}\n";
    }
    
    
    

    external by Vagner Nogueira  5217  59  5  0

    Geoip on firewall in centos 7

    Geoip on firewall in centos 7: ipblocks.sh
    #!/bin/bash
    # geoip on firewall in centos 7
    # this file: /etc/cron.daily/ipblocks.sh
    # sudo chmod +x /etc/cron.daily/ipblocks.sh
    
    ## create tmp dir
    # sudo mkdir /var/tmp/ipblocks
    ## create list on ipset
    # sudo ipset create countrylist hash:net maxelem 1000000 
    ## create rule on firewall-cmd
    # sudo firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0  -m set --match-set countrylist src -j DROP 
    # sudo firewall-cmd --reload
    
    
    TMP=/var/tmp/ipblocks
    rm -rf $TMP
    mkdir -p $TMP
    cd $TMP
    
    wget -q http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz 1> /dev/null 2> /dev/null
    tar zxf $TMP/all-zones.tar.gz
    rm -f all-zones.tar.gz
    rm -f br.zone
    rm -f us.zone
    
    for file in *.zone
    do
     cat "$file" >> $TMP/all.txt
    done
    
    while read p; do
     ipset add countrylist $p -!
    done < $TMP/all.txt
    
    logger -p cron.notice "IPSet countrylist updated."
    
    exit 0
    
    
    

    external by Allister Banks  91  0  1  0

    Uses a web geoip service and cocoaDialog to allow end users to change the time zone on their Mac (assuming they can get on the internet)

    Uses a web geoip service and cocoaDialog to allow end users to change the time zone on their Mac (assuming they can get on the internet): fix_timezone.py
    #!/usr/bin/python
    '''Offers internet-detected time zone to change on Mac'''
    
    
    import json
    import subprocess
    import sys
    import urllib2
    from gmacpyutil import cocoadialog
    
    
    def grab_geoip():
        '''returns probable timezone info via geoip lookup'''
        geoip_checksite = 'http://freegeoip.net/json/'
        response = urllib2.urlopen(geoip_checksite).read()
        if response:
            dict_response = json.loads(response)
            tzone = dict_response.get('time_zone', None)
            return tzone
        else:
            print 'foo'
    
    def change_tzone(region):
        '''heavy lifting to interact w/ sys setup'''
        cmd = ['/usr/sbin/systemsetup', '-settimezone', region]
        result = subprocess.check_call(cmd)
        print result
        return result
    
    def get_tzone():
        '''Grab current tz from sys setup'''
        cmd = ['/usr/sbin/systemsetup', '-gettimezone']
        result = subprocess.check_output(cmd)
        return result.strip()[11:]
    
    def cleanup(result):
        '''catch errors with feedback, or show success'''
        if result == 'foo':
            tooold_msg = cocoadialog.MsgBox(title="Sorry!")
            tooold_msg.SetInformativeText("There was an error setting your timezone. Please schedule a time for follow-up with the servicedesk.")
            button_pressed = tooold_msg.Show()
            button = button_pressed.split('\n')[0]
            sys.exit(1)
        elif result == 'already there':
            complete_msg = cocoadialog.MsgBox(title="Pardon")
            complete_msg.SetInformativeText("Your computer already seems to be set to the correct timezone. Please schedule a time for follow-up with the servicedesk if you still need assistance.")
            button_pressed = complete_msg.Show()
            button = button_pressed.split('\n')[0]
            if button:
                sys.exit(0)
        else:
            complete_msg = cocoadialog.MsgBox(title="Complete")
            complete_msg.SetText("Glad to be of assistance!")
            button_pressed = complete_msg.Show()
            button = button_pressed.split('\n')[0]
            if button:
                sys.exit(0)
    
    def main():
        '''gimme some main'''
        region = grab_geoip()
        current_tz = get_tzone()
        if region == current_tz:
            cleanup('already there')
        cd_title = "TimeZone Change Utility"
        welcome_prompt = cocoadialog.MsgBox(title=cd_title)
        welcome_prompt.SetText("We've detected this timezone: " + region)
        welcome_prompt.SetInformativeText("Shall we go ahead and change to that timezone?")
        welcome_prompt.SetButton1('Okay')
        welcome_prompt.SetButton2('Cancel')
        welcome_showed = welcome_prompt.Show()
        button, __ = welcome_showed.split('\n')[:2]
        if button == 'Okay':
            exit_code = change_tzone(region)
            if exit_code != 0:
                cleanup('foo')
            else:
                cleanup('success')
    
    if __name__ == '__main__':
        main()
    
    
    

    external by kslimani  79  0  1  0

    PHP Helper class which extract GeoIP ISO 3166 multi-languages country Codes list from Maxmind website

    PHP Helper class which extract GeoIP ISO 3166 multi-languages country Codes list from Maxmind website: maxmind-iso-3166.php
    <?php
    
    /**
     * Helper class which extract GeoIP ISO 3166 country Codes list from Maxmind website.
     */
    class MaxMindIso3166
    {
        /**
         * Maxmind CSV download url.
         *
         * @var string
         */
        protected static $csvUrl = "http://dev.maxmind.com/static/csv/codes/iso3166.csv";
    
        /**
         * CSV cache file pathname.
         *
         * @var string
         */
        protected static $cachefile = '/tmp/iso3166.csv';
    
        /**
         * Expiry in seconds.
         *
         * @var int
         */
        protected static $expiry = 3600;
    
        /**
         * Download country codes in CSV format.
         *
         * @return string The CSV raw data
         */
        protected static function downloadCsv()
        {
            return trim(file_get_contents(self::$csvUrl));
        }
    
        /**
         * Verify is temporary CSV cache file is expired.
         *
         * @return bool true if expired, otherwise false
         */
        protected static function fileIsExpired()
        {
            return ((time() - filemtime(self::$cachefile)) > self::$expiry);
        }
    
        /**
         * Get country codes in CSV format.
         *
         * @return string The CSV raw data
         */
        protected static function getCsv()
        {
            if (is_file(self::$cachefile) && !self::fileIsExpired()) {
    
                // Get from cache file
                return file_get_contents(self::$cachefile);
            } else {
                // Download & save to cache file
                $csv = self::downloadCsv();
                file_put_contents(self::$cachefile, $csv);
    
                return $csv;
            }
        }
    
        /**
         * Get Maxmind GeoIP ISO 3166 Country Codes.
         *
         * @param string $inLocale Optional format locale 
         *        to use to translate country name
         *
         * @return array The country codes
         */
        public static function getCountryCodes($inLocale = 'fr')
        {
            $countryCodes = [];
            $lines = explode("\n", self::getCsv());
    
            foreach ($lines as $line) {
                list($code, $name) = str_getcsv($line);
    
                // Use Locale to translate country name
                $countryName = Locale::getDisplayRegion(
                    sprintf('-%s', $code),
                    $inLocale
                );
    
                // If translation failed, keep original name
                // Always happen for 'A1', 'A2' and 'O1' codes
                if ($countryName === $code) {
                    $countryName = $name;
                }
    
                $countryCodes[$code] = $countryName;
            }
    
            return $countryCodes;
        }
    }
    
    $codes = MaxMindIso3166::getCountryCodes();
    var_export($codes);
    
    
    

    external by nap  45  0  1  0

    Simple MBOX parser that match IP to GeoIP database to get the location of all failed attempt to connect to my NAS via SSH

    Simple MBOX parser that match IP to GeoIP database to get the location of all failed attempt to connect to my NAS via SSH: mbox_parser.py
    __author__ = 'unary'
    
    import re
    import email
    import mailbox
    import calendar
    
    import pygeoip
    
    from pprint import pprint
    
    ip_regexp = r'[0-9]+(?:\.[0-9]+){3}'
    timestamp_regexp = r'(?:{0}) (?:{1})(?:[0-9\:\ ]+)'.format('|'.join(calendar.day_abbr[1:]),
                                                               '|'.join(calendar.month_abbr[1:]))
    
    
    def main():
        # GeoLiteCity.dat available at http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
        ip = {}
        gic = pygeoip.GeoIP('etc/GeoLiteCity.dat')
        for k, v in mailbox.mbox('etc/SYNO.mbox').items():
            message = mailbox.mboxMessage(v)
            payload = email.message_from_string(str(message)).get_payload()
            new_ip = re.findall(ip_regexp, str(payload))
    
            if not len(new_ip):
                continue
    
            new_ip = new_ip[0]
            new_time = re.findall(timestamp_regexp, str(payload))
            if new_ip[0] in ip:
                ip[new_ip].append(new_time[0])
    
            ip.update({
                new_ip: {'time': new_time,
                         'geo': gic.record_by_addr(new_ip)}
            })
    
        pprint(ip)
    
    if __name__ == '__main__':
        main()
    
    
    • Public Snippets
    • Channels Snippets