/**
  * @param Request $request
  * @return Response
  */
 protected function proceed(Http $httpUri, Request $request)
 {
     $httpUri = $httpUri->parse($this->moduleOptions->getApiUrl() . $httpUri->toString());
     $request->setUri($httpUri);
     $this->httpClient->setAuth($this->moduleOptions->getUserName(), $this->moduleOptions->getPassword());
     $this->httpClient->setOptions(array('sslverifypeer' => false));
     return $this->httpClient->send($request);
 }
Exemple #2
0
 /**
  * Test we can properly use Basic HTTP authentication
  *
  */
 public function testHttpAuthBasic()
 {
     $this->client->setUri($this->baseuri . 'testHttpAuth.php');
     $this->client->setParameterGet(array('user' => 'alice', 'pass' => 'secret', 'method' => 'Basic'));
     // First - fail password
     $this->client->setAuth('alice', 'wrong');
     $res = $this->client->send();
     $this->assertEquals(401, $res->getStatusCode(), 'Expected HTTP 401 response was not recieved');
     // Now use good password
     $this->client->setAuth('alice', 'secret');
     $res = $this->client->send();
     $this->assertEquals(200, $res->getStatusCode(), 'Expected HTTP 200 response was not recieved');
 }
 private function search($query, $geolocate)
 {
     $query = urlencode($query);
     $client = new Client();
     $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl');
     $client->setOptions(['timeout' => 60]);
     $client->setAuth(BING_SEARCH_API_KEY, BING_SEARCH_API_KEY);
     $client->setUri('https://api.datamarket.azure.com/Bing/Search/v1/Web');
     $searchParams = $geolocate ? ['Market' => "'es-Cl'", 'Latitude' => '-33.45', 'Longitude' => '-70.6667', 'Query' => "'{$query}'", '$format' => 'json'] : ['Query' => "'{$query}'", '$format' => 'json'];
     $client->setParameterGet($searchParams);
     $response = $client->send();
     return $response->isSuccess() ? json_decode($response->getBody()) : null;
 }
 /**
  * Requests RAYNET Cloud CRM REST API. Check https://s3-eu-west-1.amazonaws.com/static-raynet/webroot/api-doc.html for any further details.
  *
  * @param $serviceName string URL service name
  * @param $method string Http method
  * @param $request array request
  * @return \Zend\Http\Response response
  */
 private function callRaynetcrmRestApi($serviceName, $method, $request)
 {
     $client = new Client('', array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false)));
     $client->setMethod($method);
     $client->setUri($this->buildUrl($serviceName));
     $client->setHeaders(array('X-Instance-Name' => $this->fInstanceName, 'Content-Type' => 'application/json; charset=UTF-8'));
     $client->setAuth($this->fUserName, $this->fApiKey);
     if ($method === self::HTTP_METHOD_GET) {
         $client->setParameterGet($request);
     } else {
         $client->setRawBody(Json::encode($request));
     }
     return $client->send();
 }
Exemple #5
0
 /**
  * Make an OAI-PMH request.  Die if there is an error; return a SimpleXML object
  * on success.
  *
  * @param string $verb   OAI-PMH verb to execute.
  * @param array  $params GET parameters for ListRecords method.
  *
  * @return object        SimpleXML-formatted response.
  */
 protected function sendRequest($verb, $params = [])
 {
     // Debug:
     if ($this->verbose) {
         $this->write("Sending request: verb = {$verb}, params = " . print_r($params, true));
     }
     // Set up retry loop:
     while (true) {
         // Set up the request:
         $this->client->resetParameters();
         $this->client->setUri($this->baseURL);
         $this->client->setOptions(['timeout' => $this->timeout]);
         // Set authentication, if necessary:
         if ($this->httpUser && $this->httpPass) {
             $this->client->setAuth($this->httpUser, $this->httpPass);
         }
         // Load request parameters:
         $query = $this->client->getRequest()->getQuery();
         $query->set('verb', $verb);
         foreach ($params as $key => $value) {
             $query->set($key, $value);
         }
         // Perform request and die on error:
         $result = $this->client->setMethod('GET')->send();
         if ($result->getStatusCode() == 503) {
             $delayHeader = $result->getHeaders()->get('Retry-After');
             $delay = is_object($delayHeader) ? $delayHeader->getDeltaSeconds() : 0;
             if ($delay > 0) {
                 if ($this->verbose) {
                     $this->writeLine("Received 503 response; waiting {$delay} seconds...");
                 }
                 sleep($delay);
             }
         } else {
             if (!$result->isSuccess()) {
                 throw new \Exception('HTTP Error');
             } else {
                 // If we didn't get an error, we can leave the retry loop:
                 break;
             }
         }
     }
     // If we got this far, there was no error -- send back response.
     return $this->processResponse($result->getBody());
 }
 /**
  * Create a http client service
  *
  * @param ServiceLocatorInterface $serviceLocator
  * @return Client
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $config = $serviceLocator->get('Config');
     $client = new Client();
     if (!empty($config[$this->configKey])) {
         $clientOptions = $config[$this->configKey];
         if (isset($clientOptions['uri'])) {
             $client->setUri($clientOptions['uri']);
             unset($clientOptions['uri']);
         }
         if (isset($clientOptions['auth'])) {
             $auth = $clientOptions['auth'];
             $client->setAuth(isset($auth['user']) ? $auth['user'] : '', isset($auth['password']) ? $auth['password'] : '', isset($auth['type']) ? $auth['type'] : $client::AUTH_BASIC);
             unset($clientOptions['auth']);
         }
         $client->setOptions($config[$this->configKey]);
     }
     return $client;
 }
Exemple #7
0
 /**
  * Handles all GET requests to a web service
  *
  * @param   string $path  Path
  * @param   array  $parms Array of GET parameters
  * @param   string $type  Type of a request ("xml"|"json")
  * @return  mixed  decoded response from web service
  * @throws  Zend_Service_Delicious_Exception
  */
 public function makeRequest($path, array $params = array(), $type = 'xml')
 {
     // if previous request was made less then 1 sec ago
     // wait until we can make a new request
     $timeDiff = microtime(true) - self::$lastRequestTime;
     if ($timeDiff < 1) {
         usleep((1 - $timeDiff) * 1000000);
     }
     $this->httpClient->setAuth($this->authUname, $this->authPass);
     $this->httpClient->setOptions(array('ssltransport' => 'ssl'));
     $request = new HttpRequest();
     $request->setMethod(HttpRequest::METHOD_GET);
     switch ($type) {
         case 'xml':
             $request->setUri(self::API_URI);
             break;
         case 'json':
             $params['raw'] = true;
             $request->setUri(self::JSON_URI);
             break;
         default:
             throw new Exception('Unknown request type');
     }
     self::$lastRequestTime = microtime(true);
     $request->getQuery()->fromArray($params);
     $response = $this->httpClient->send($request);
     if (!$response->isSuccess()) {
         throw new Exception("Http client reported an error: '{$response->getReasonPhrase()}'");
     }
     $responseBody = $response->getBody();
     switch ($type) {
         case 'xml':
             $dom = new \DOMDocument();
             if (!@$dom->loadXML($responseBody)) {
                 throw new Exception('XML Error');
             }
             return $dom;
         case 'json':
             return \Zend\Json\Decoder::decode($responseBody);
     }
 }
 /**
  * Sets all general parameters for all api calls
  *
  * @param array $apiCallParameters the api call parameters array
  *
  * @return void
  *
  * @throws \Msl\RemoteHost\Exception\BadApiConfigurationException
  */
 public function setGeneralApiCallParameters(array $apiCallParameters)
 {
     if (!isset($apiCallParameters['host'])) {
         throw new BadApiConfigurationException(sprintf('[%s] Missing parameter for GENERAL API configuration: host.', $this->getApiName()));
     }
     // Setting api call parameters
     $this->host = $apiCallParameters['host'];
     // Setting port
     if (isset($apiCallParameters['port'])) {
         $this->port = $apiCallParameters['port'];
     }
     // Setting user
     if (isset($apiCallParameters['user'])) {
         $this->user = $apiCallParameters['user'];
     }
     // Setting password
     if (isset($apiCallParameters['password'])) {
         $this->password = $apiCallParameters['password'];
     }
     // If defined, we set user and password parameters for authentication purposes
     if ($this->user && $this->password) {
         $this->client->setAuth($this->user, $this->password);
     }
 }
Exemple #9
0
 public function sendMessage($postdata)
 {
     $defaults = array('publisher' => $this->config['publisher'], 'provider' => '', 'message' => '', 'message_plain' => '', 'lang' => '', 'property_reference' => '', 'salutation_code' => '', 'firstname' => '', 'lastname' => '', 'legal_name' => '', 'street' => '', 'postal_code' => '', 'locality' => '', 'phone' => '', 'mobile' => '', 'fax' => '', 'email' => '');
     $postdata = array_merge($defaults, $postdata);
     $postdata['publisher'] = $this->config['publisher'];
     if ($postdata['message'] && !$postdata['message_plain']) {
         $postdata['message'] = $this->sanitizeHtml($postdata['message']);
         $postdata['message_plain'] = strip_tags($postdata['message']);
     }
     if (!$postdata['message'] && $postdata['message_plain']) {
         $postdata['message_plain'] = strip_tags($postdata['message_plain']);
         $postdata['message'] = $this->sanitizeHtml($postdata['message_plain']);
     }
     if ($postdata['message'] && $postdata['message_plain']) {
         $postdata['message_plain'] = strip_tags($postdata['message_plain']);
         $postdata['message'] = $this->sanitizeHtml($postdata['message_plain']);
     }
     $config = array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FRESH_CONNECT => true));
     $query = array();
     $uri = $this->config['url'] . '/msg?' . http_build_query($query);
     $client = new HttpClient($uri, $config);
     $client->setHeaders(array('Accept' => 'application/json; charset=UTF-8', 'Content-Type' => 'application/json'));
     $client->setMethod('POST');
     $client->setRawBody(Json::encode($postdata));
     $client->setEncType(HttpClient::ENC_FORMDATA);
     $client->setAuth($this->config['username'], $this->config['password'], \Zend\Http\Client::AUTH_BASIC);
     $response = $client->send();
     return $response->getContent();
 }
Exemple #10
0
 /**
  * Creates and configures a http client
  *
  * @return Client
  */
 protected function initHttpClient()
 {
     $httpClient = new Client($this->url);
     if (isset($this->login) && isset($this->password)) {
         $httpClient->setAuth($this->login, $this->password);
     }
     $httpClient->setHeaders($this->requestHeaders);
     $httpClient->setMethod($this->requestMethod);
     return $httpClient;
 }
Exemple #11
0
 /**
  * Test setAuth (dynamic method) fails when trying to use an unsupported
  * authentication scheme
  *
  */
 public function testExceptUnsupportedAuthDynamic()
 {
     $this->setExpectedException('Zend\\Http\\Exception\\InvalidArgumentException', 'Invalid or not supported authentication type: \'SuperStrongAlgo\'');
     $this->_client->setAuth('shahar', '1234', 'SuperStrongAlgo');
 }
Exemple #12
0
 public function logMsg($message, $priority = 7)
 {
     $config = array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FRESH_CONNECT => true));
     $query = array();
     $uri = $this->config['url'] . '/msg?' . http_build_query($query);
     $client = new HttpClient($uri, $config);
     $client->setHeaders(array('Accept' => 'application/json; charset=UTF-8', 'Content-Type' => 'application/json'));
     $client->setMethod('POST');
     $client->setRawBody(Json::encode(array('software' => $this->config['software'], 'message' => $message, 'priority' => $priority, 'priorityName' => array_search($priority, $this->priorities), 'timestamp' => date('Y-m-dTH:i:s', time()))));
     $client->setEncType(HttpClient::ENC_FORMDATA);
     $client->setAuth($this->config['username'], $this->config['password'], \Zend\Http\Client::AUTH_BASIC);
     try {
         $response = $client->send();
     } catch (\Exception $e) {
         //probably timeout thats ok ^^;
     }
     return true;
 }
 /**
  * {@inheritdoc}
  * @see \Saml\Ecp\Authentication\Method\MethodInterface::configureHttpClient()
  */
 public function configureHttpClient(Client $httpClient)
 {
     $httpClient->setAuth($this->_options->get(self::OPT_USERNAME), $this->_options->get(self::OPT_PASSWORD), Client::AUTH_BASIC);
 }
Exemple #14
0
 public function testIfClientDoesNotLooseAuthenticationOnRedirect()
 {
     // set up user credentials
     $user = '******';
     $password = '******';
     $encoded = Client::encodeAuthHeader($user, $password, Client::AUTH_BASIC);
     // set up two responses that simulate a redirection
     $testAdapter = new Test();
     $testAdapter->setResponse("HTTP/1.1 303 See Other\r\n" . "Location: http://www.example.org/part2\r\n\r\n" . "The URL of this page has changed.");
     $testAdapter->addResponse("HTTP/1.1 200 OK\r\n\r\n" . "Welcome to this Website.");
     // create client with HTTP basic authentication
     $client = new Client('http://www.example.org/part1', array('adapter' => $testAdapter, 'maxredirects' => 1));
     $client->setAuth($user, $password, Client::AUTH_BASIC);
     // do request
     $response = $client->setMethod('GET')->send();
     // the last request should contain the Authorization header
     $this->assertTrue(strpos($client->getLastRawRequest(), $encoded) !== false);
 }
Exemple #15
0
 /**
  *
  * @param string  'GET' 'HEAD' 'POST' 'PUT' 'DELETE';
  * @param Query $query
  * @param int|string $id
  * @param bool see $ifMatch $rewriteIfExist and $createIfAbsent in {@see DataStoreAbstract}
  * @return Client
  */
 protected function initHttpClient($method, Query $query = null, $id = null, $ifMatch = false)
 {
     $url = !$id ? $this->url : $this->url . '/' . $this->encodeString($id);
     if (isset($query)) {
         $rqlString = RqlParser::rqlEncode($query);
         $url = $url . '?' . $rqlString;
     }
     $httpClient = new Client($url, $this->options);
     $headers['Content-Type'] = 'application/json';
     $headers['Accept'] = 'application/json';
     if ($ifMatch) {
         $headers['If-Match'] = '*';
     }
     $httpClient->setHeaders($headers);
     if (isset($this->login) && isset($this->password)) {
         $httpClient->setAuth($this->login, $this->password);
     }
     $httpClient->setMethod($method);
     return $httpClient;
 }
Exemple #16
0
 /**
  * @return Http\Client
  */
 protected function getHttpClient()
 {
     $client = new Http\Client();
     $client->setOptions(array('maxredirects' => 0, 'timeout' => 60));
     $client->setAuth('api', $this->getOptions()->getApiKey());
     return $client;
 }
Exemple #17
0
 /**
  * Download data from server
  *
  * @return    String
  * @throws    Exceptions\Fetch
  * @throws    \Exception
  */
 protected function download()
 {
     try {
         $url = $this->getApiEndpointUrl();
     } catch (\Exception $e) {
         $this->result->addError($e->getMessage());
         throw new Exceptions\Fetch('Stopped sync. Cannot start synchronization because API URL is invalid');
     }
     $client = new HttpClient($url);
     if (!empty($this->config->user) && !empty($this->config->password)) {
         $client->setAuth($this->config->user, $this->config->password);
     }
     $this->result->addInfo('Send request to: ' . $url);
     /** @var Response $response */
     $response = $client->send();
     if ($response->isSuccess()) {
         $responseBody = $response->getBody();
         if (!$this->storeDownloadedData($responseBody)) {
             throw new Exceptions\Fetch('Was not able to store downloaded data in a local cache (data/cache/libadmin.json)');
         }
         return $responseBody;
     } else {
         throw new Exceptions\Fetch('Request failed: ' . $response->getReasonPhrase());
     }
 }