gaiar
8/10/2017 - 7:48 PM

maxmind-vpn-detection.php

/**
 * @param $app
 * @return int:
 *  -4: Error
 *  -3: Googlebot
 *  -2: Found locally, not a VPN
 *  -1: Looked up, not a VPN
 *   1: Looked up, VPN
 *   2: Found locally, VPN
 */
function isAnonymous($app)
{
    // Trade accuracy for TTFB for Googlebot
    if(strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false) {
        return -3;
    }

    $sql  = "SELECT * FROM maxmind WHERE ip = ?";
    $post = $app['db']->fetchAssoc($sql, array(getClientIp()));
    if($post === false) {
        try {
            $client = new Client(MAXMIND_USR, MAXMIND_KEY);
            $record = $client->insights(getClientIp());
            $city = @json_decode($record->city->names, true)['en'];
            $sql = "INSERT INTO maxmind (ip, country, post_code, is_anonymous_proxy, isp, organization, user_type, geoname_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $app['db']->executeUpdate($sql, array(
                getClientIp(),
                $record->country->isoCode,
                $record->postal->code,
                $record->traits->isAnonymousProxy,
                $record->traits->isp,
                $record->traits->organization,
                $record->traits->userType,
                is_string($city) ? $city : '(error)'
            ));

            if (in_array($record->traits->userType, array('content_delivery_network', 'hosting', 'router'))
                || $record->traits->isAnonymousProxy == 1
            ) {
                return 1;
            }
            return -1;
        } catch (\Exception $e) {
            return -4;
        }
    } else {
        if($post['is_anonymous_proxy']) {
            return 2;
        }
        return -2;
    }
}