Make a Geolocation API call

@param string $ip        The IP address
@param $apiKey           ipstack.com API key
@return null|string      JSON formated response
@throws \Zend_Http_Client_Exception
513256
private function getLocationJson($ip, $apiKey)
    {

        $endpoint = sprintf($this->endpointFormat, $ip, $apiKey);

        $client = $this->httpClientFactory->create();
        $client->setUri($endpoint);
        $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);

        // Dependant on third party API, wrapping in try/catch block.
        // On error notify bugsnag and proceed (return null)
        try {
            return $client->request()->getBody();
        } catch (\Exception $e) {
            $this->bugsnag->notifyException($e);
            return null;
        }
    }
3037
public static function checkIP($ip = null, $purpose = 'location', $deep_detect = true)
    {
        $output = null;
        if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
            $ip = $_SERVER['REMOTE_ADDR'];
            if ($deep_detect) {
                if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
                    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                }
                if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) {
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
                }
            }
        }
        $purpose = str_replace(['name', "\n", "\t", ' ', '-', '_'], null, strtolower(trim($purpose)));
        $support = ['country', 'countrycode', 'state', 'region', 'city', 'location', 'address'];
        $continents = [
            'AF' => 'Africa',
            'AN' => 'Antarctica',
            'AS' => 'Asia',
            'EU' => 'Europe',
            'OC' => 'Australia (Oceania)',
            'NA' => 'North America',
            'SA' => 'South America',
        ];
        if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
            $ipdat = @json_decode(file_get_contents('http://www.geoplugin.net/json.gp?ip='.$ip));
            if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
                switch ($purpose) {
                    case 'location':
                        $output = [
                            'city'           => @$ipdat->geoplugin_city,
                            'state'          => @$ipdat->geoplugin_regionName,
                            'country'        => @$ipdat->geoplugin_countryName,
                            'countryCode'    => @$ipdat->geoplugin_countryCode,
                            'continent'      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
                            'continent_code' => @$ipdat->geoplugin_continentCode,
                            'latitude'       => @$ipdat->geoplugin_latitude,
                            'longitude'      => @$ipdat->geoplugin_longitude,
                            'currencyCode'   => @$ipdat->geoplugin_currencyCode,
                            'areaCode'       => @$ipdat->geoplugin_areaCode,
                            'dmaCode'        => @$ipdat->geoplugin_dmaCode,
                            'region'         => @$ipdat->geoplugin_region,
                        ];
                        break;
                    case 'address':
                        $address = [$ipdat->geoplugin_countryName];
                        if (@strlen($ipdat->geoplugin_regionName) >= 1) {
                            $address[] = $ipdat->geoplugin_regionName;
                        }
                        if (@strlen($ipdat->geoplugin_city) >= 1) {
                            $address[] = $ipdat->geoplugin_city;
                        }
                        $output = implode(', ', array_reverse($address));
                        break;
                    case 'city':
                        $output = @$ipdat->geoplugin_city;
                        break;
                    case 'state':
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case 'region':
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case 'country':
                        $output = @$ipdat->geoplugin_countryName;
                        break;
                    case 'countrycode':
                        $output = @$ipdat->geoplugin_countryCode;
                        break;
                }
            }
        }

        return $output;
    }
1114777
static function create($apikey, array $conf = []) {
        $clnt = new YunpianClient();
        $clnt->conf->init()->with($apikey, $conf);
        $clnt->initHttp($clnt->conf); // YunpianGuzzle->initHttp
        return $clnt;
    }
271623
public static function update($id, $params, $apiKey = null)
    {
        $class = get_class();
        return self::_scopedUpdate($class, $id, $params, $apiKey);
    }
221455
@Override
    protected Client getClient(String apiKey) throws IOException {
        Client client;
        synchronized (mutex) {
            client = clientCache.get(apiKey);
        }

        if (client == null) {
            client = super.getClient(apiKey);
            synchronized (mutex) {
                if (client != null) {
                    clientCache.put(apiKey, client);
                }
            }
        }

        return client;
    }
872030
public static String getLocationByIp(String ip) throws IOException, XPathExpressionException,
            ParserConfigurationException {
        return evaluate(ValueConsts.IP_REGION_XPATH, getHtmlFromUrl("http://ip.chinaz.com/" + ip));
    }
1019229
public static function create($params = null, $apiKey = null)
    {
        return self::_create(get_class(), $params, $apiKey);
    }
553978
public static function getUserClient($organization = null, $apiKey = null, $options = [])
    {
        $baseUrl = BaseClient::DEFAULT_API_BASE_URL;

        //bc compability, when first param was $options
        if (\is_array($organization)) {
            $options = $organization;
            $organization = null;
            $apiKey = null;
        }
        if (isset($options[self::API_BASE_URL])) {
            $baseUrl = $options[self::API_BASE_URL];
        }

        $client = self::getGuzzleClient($baseUrl, $options);

        return new UserClient($client, $organization, $apiKey);
    }
478158
public function place(ServerRequestInterface $request, Tree $tree): ResponseInterface
    {
        $query = $request->get('query', '');
        $data  = [];

        foreach ($this->search_service->searchPlaces($tree, $query) as $place) {
            $data[] = ['value' => $place->gedcomName()];
        }

        if (empty($data) && $tree->getPreference('GEONAMES_ACCOUNT')) {
            // No place found? Use an external gazetteer
            $url =
                'http://api.geonames.org/searchJSON' .
                '?name_startsWith=' . urlencode($query) .
                '&lang=' . WT_LOCALE .
                '&fcode=CMTY&fcode=ADM4&fcode=PPL&fcode=PPLA&fcode=PPLC' .
                '&style=full' .
                '&username=' . $tree->getPreference('GEONAMES_ACCOUNT');

            // try to use curl when file_get_contents not allowed
            if (ini_get('allow_url_fopen')) {
                $json = file_get_contents($url);
            } elseif (function_exists('curl_init')) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $json = curl_exec($ch);
                curl_close($ch);
            } else {
                return response([]);
            }

            $places = json_decode($json, true);
            if (isset($places['geonames']) && is_array($places['geonames'])) {
                foreach ($places['geonames'] as $k => $place) {
                    $data[] = ['value' => $place['name'] . ', ' . $place['adminName2'] . ', ' . $place['adminName1'] . ', ' . $place['countryName']];
                }
            }
        }

        return response($data);
    }
1296329
public static function make($apiKey = null, $registerDefaultCallback = true)
    {
        $config = new Config($apiKey ?: getenv('AFTERBUG_API_KEY'));

        $client = new static($config, static::makeGuzzle($config));

        if ($registerDefaultCallback) {
            $client->registerDefaultCallbacks();
        }

        return $client;
    }
1333605
public static function create($params = null, $apiKey = null)
    {
        $urlMod = "";

        if ((isset($params['verify']) && is_array($params['verify'])) || (isset($params['verify_strict']) && is_array($params['verify_strict']))) {
            $verify = "";
            if (isset($params['verify'])) {
                $verify = $params['verify'];
                unset($params['verify']);
            }

            $verify_strict = "";
            if (isset($params['verify_strict'])) {
                $verify_strict = $params['verify_strict'];
                unset($params['verify_strict']);
            }

            $urlMod = "?";

            if (is_array($verify)) {
                foreach ($verify as $verification) {
                    $urlMod .= "verify[]=" . $verification . "&";
                }
            }

            if (is_array($verify_strict)) {
                foreach ($verify_strict as $verification_strict) {
                    $urlMod .= "verify_strict[]=" . $verification_strict . "&";
                }
            }
        }

        if (!isset($params['address']) || !is_array($params['address'])) {
            $clone = $params;
            unset($params);
            $params['address'] = $clone;
        }

        return self::_create(get_class(), $params, $apiKey, $urlMod);
    }
667609
public static function aqi($cityName, $apikey)
    {
        $url = self::AQI_API . '/aqi';

        return self::send($url, ['city' => $cityName], ["apikey: $apikey"]);
    }
511066
private function createSocketStream(ApiClient $apiClient, HttpRequest $request) {
		if ($request->isSecureConnection()) {
			if (!extension_loaded('openssl')) {
				throw new \Exception("You have to enable OpenSSL.");
			}
		}

		$proxyUrl = $this->readEnvironmentVariable(self::ENVIRONMENT_VARIABLE_PROXY_URL);
		if ($proxyUrl !== null) {
			$host = parse_url($proxyUrl, PHP_URL_HOST);
			$port = parse_url($proxyUrl, PHP_URL_PORT);
			if(empty($port)) {
				throw new ConnectionException($request->getUrl(), $request->getLogToken(), "The Proxy URL must contain a port number.");
			}
			
		} else {
			$host = ($request->isSecureConnection() ? $this->getSslProtocol() . '://' : '') . $request->getHost();
			$port = $request->getPort();
			if(empty($port)) {
				$port = $request->isSecureConnection() ? 443 : 80;
			}	
		}			
		$socket = $host . ':' . $port;

		$filePointer = @stream_socket_client($socket, $errno, $errstr, $apiClient->getConnectionTimeout(), STREAM_CLIENT_CONNECT,
				$this->createStreamContext($apiClient, $request));

		if ($filePointer === false) {
			throw new ConnectionException($request->getUrl(), $request->getLogToken(), $errstr);
		}

		if (!(get_resource_type($filePointer) == 'stream')) {
			$errorMessage = 'Could not connect to the server. The returned socket was not a stream.';
			throw new ConnectionException($request->getUrl(), $request->getLogToken(), $errorMessage);
		}

		return $filePointer;
	}
647747
private function find($ip = null)
    {
        // If IP not set, user remote IP
        $ip = $ip ?: $this->remote_ip;

        // Check cache for location
        if ($this->config('cache', 'none') !== 'none' && $location = $this->getCache()->get($ip)) {
            $location->cached = true;

            return $location;
        }

        // Check if the ip is not local or empty
        if ($this->isValid($ip)) {
            try {
                // Find location
                $location = $this->getService()->locate($ip);

                // Set currency if not already set by the service
                if (!$location->currency) {
                    $location->currency = $this->getCurrency($location->iso_code);
                }

                // Set default
                $location->default = false;

                return $location;
            }
            catch (\Exception $e) {
                if ($this->config('log_failures', true) === true) {
                    $log = new Logger('geoip');
                    $log->pushHandler(new StreamHandler(storage_path('logs/geoip.log'), Logger::ERROR));
                    $log->addError($e);
                }
            }
        }

        return $this->getService()->hydrate($this->default_location);
    }
651113
public static function setKey($key, ClientInterface $client = null)
	{
		self::$api = new Api($key, $client);

		return self::$api;
	}
1139366
function resolve($ip){
      
      $url = \Config::get('laravel-4-freegeoip::freegeoipURL').$ip;
      
      $ch = curl_init();
      curl_setopt ($ch, CURLOPT_URL, $url);
      curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, \Config::get('laravel-4-freegeoip::timeout'));
      
      $file_contents = curl_exec($ch);    
      curl_close($ch);
      
      $data = json_decode($file_contents);
      
      if($data == NULL)
          throw new \Exception("Problems in retrieving data from http://freegeoip.net");

      return $data;
    }
396205
public function connect($serverLogin, $apikey)
    {
        $this->apiKey = $apikey;
        $this->serverLogin = $serverLogin;

        if (empty($this->apiKey)) {
            $this->console->writeln('MxKarma error: You need to define a api key');

            return;
        }

        if (empty($this->serverLogin)) {
            $this->console->writeln('MxKarma error: You need to define server login');

            return;
        }

        $params = [
            "serverLogin" => $serverLogin,
            "applicationIdentifier" => "eXpansion v ".AbstractApplication::EXPANSION_VERSION,
            "testMode" => "false",
        ];

        $this->console->writeln('> MxKarma attempting to connect...');
        $this->http->get(
            $this->buildUrl(
                "startSession", $params),
            [$this, "xConnect"]
        );
    }