Esempio n. 1
0
 public function citation()
 {
     parent::results();
     $style = $this->request->getParam("style", false, "mla");
     $items = array();
     $results = $this->response->get("results");
     // header("Content-type: application/json");
     $x = 1;
     foreach ($results->getRecords() as $result) {
         $id = "ITEM={$x}";
         $record = $result->getXerxesRecord()->toCSL();
         $record["id"] = $id;
         $items[$id] = $record;
         $x++;
     }
     $json = json_encode(array("items" => $items));
     // header("Content-type: application/json"); echo $json; exit;
     $url = "http://127.0.0.1:8085?responseformat=html&style={$style}";
     $client = new Client();
     $client->setUri($url);
     $client->setHeaders("Content-type: application/json");
     $client->setHeaders("Expect: nothing");
     $client->setRawData($json)->setEncType('application/json');
     $response = $client->request('POST')->getBody();
     echo $response;
     exit;
 }
Esempio n. 2
0
 /**
  * Return the singleton instance of the HTTP Client. Note that
  * the instance is reset and cleared of previous parameters and
  * Authorization header values.
  *
  * @return Zend\Http\Client
  */
 public static function getHttpClient()
 {
     if (!isset(self::$httpClient)) {
         self::$httpClient = new HTTPClient();
     } else {
         self::$httpClient->setHeaders('Authorization', null);
         self::$httpClient->resetParameters();
     }
     return self::$httpClient;
 }
Esempio n. 3
0
 /**
  * @throws Exception\ConfigWasNotProvided
  * @throws Exception\TokenWasNotProvided
  */
 public function __construct()
 {
     if (!self::getConfig()) {
         throw new Exception\ConfigWasNotProvided();
     }
     if (!self::getToken()) {
         throw new Exception\TokenWasNotProvided();
     }
     $this->_client = new \Zend\Http\Client();
     $this->_client->setHeaders(['x-auth' => self::getToken()]);
 }
 /**
  * {@inheritDoc}
  */
 public function get($uri, array $headers = [])
 {
     $this->client->resetParameters();
     $this->client->setMethod('GET');
     $this->client->setHeaders(new Headers());
     $this->client->setUri($uri);
     if (!empty($headers)) {
         $this->injectHeaders($headers);
     }
     $response = $this->client->send();
     return new Response($response->getStatusCode(), $response->getBody(), $this->prepareResponseHeaders($response->getHeaders()));
 }
Esempio n. 5
0
 /**
  * Write using a stream
  *
  * @param $path
  * @param $resource
  * @param null $config
  * @return array|bool
  */
 public function writeStream($path, $resource, Config $config)
 {
     $username = '******';
     $password = '******';
     $auth = base64_encode($username . ':' . $password);
     $this->client->setUri('http://192.168.10.47/api/wstest/upload/fg');
     // $this->client->setUri('http://files.local/api/v2/fs');
     $this->client->setMethod('POST');
     $headers = ['Accept' => '*/*', 'Cache-Control' => 'no-cache', 'Authorization' => 'Basic ' . $auth, 'X-File-Name' => 'todo.txt', 'Content-Type' => 'application/x-www-form-urlencoded'];
     $this->client->setHeaders($headers);
     file_put_contents('tmp', $resource);
     //        $this->client->setFileUpload('todo.txt', 'todo_txt', $resource);
     $text = 'this is some plain text';
     $this->client->setFileUpload('some_text.txt', 'some_text_txt', $text, 'text/plain');
     prn($this->client->send()->getContent());
     exit;
     $location = $this->applyPathPrefix($path);
     $config = Util::ensureConfig($config);
     $this->ensureDirectory(dirname($location));
     $this->client->setMethod('POST');
     $this->client->setUri($this->api_url);
     $this->client->setParameterPOST(array_merge($this->auth_param, ['filename' => $path]));
     $this->client->setHeaders(['wp_path' => $path]);
     file_put_contents('tmp', $resource);
     $this->client->setFileUpload('tmp', 'form');
     $response = $this->client->send();
     $path = json_decode($response->getContent())->file_id;
     $type = 'wepo_fs';
     $result = compact('contents', 'type', 'size', 'path');
     if ($visibility = $config->get('visibility')) {
         $result['visibility'] = $visibility;
     }
     return $result;
 }
 protected function getClient($url)
 {
     $http_client = new HttpClient(null, ['timeout' => $this->timeout]);
     $http_client->setHeaders(['User-Agent' => 'OpenErpByJsonRpc by ZendJsonRpc']);
     if (null !== $this->cookie) {
         $http_client->addCookie($this->cookie);
     }
     $this->client = new Client($url, $http_client);
     return $this->client;
 }
Esempio n. 7
0
 /**
  * @group ZF2-78
  * @dataProvider parameterArrayProvider
  */
 public function testContentTypeAdditionlInfo($params)
 {
     $content_type = 'application/x-www-form-urlencoded; charset=UTF-8';
     $this->client->setUri($this->baseuri . 'testPostData.php');
     $this->client->setHeaders(array('Content-Type' => $content_type));
     $this->client->setMethod(\Zend\Http\Request::METHOD_POST);
     $this->client->setParameterPost($params);
     $this->client->send();
     $request = Request::fromString($this->client->getLastRawRequest());
     $this->assertEquals($content_type, $request->getHeaders()->get('Content-Type')->getFieldValue());
 }
 public function doPostRequest()
 {
     $url = 'http://www.mvg-live.de/MvgLive/mvglive/rpc/newstickerService';
     $client = new Client();
     $client->setUri($url);
     $client->setMethod(\Zend\Http\Request::METHOD_POST);
     $headers = array('Origin' => 'http://www.mvg-live.de', 'Accept-Encoding' => 'gzip, deflate', 'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,da;q=0.2', 'X-GWT-Module-Base' => 'http://www.mvg-live.de/MvgLive/mvglive/', 'Connection' => 'keep-alive', 'Cache-Control' => 'no-cache', 'Pragma' => 'no-cache', 'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36', 'Content-Type' => 'text/x-gwt-rpc; charset=UTF-8', 'Accept' => '*/*', 'X-GWT-Permutation' => '1DD521F1FA9966B50432692AB421CD55', 'Referer' => 'http://www.mvg-live.de/MvgLive/MvgLive.jsp', 'DNT' => '1');
     $client->setHeaders($headers);
     $client->setRawBody('7|0|4|http://www.mvg-live.de/MvgLive/mvglive/|7690A2A77A0295D3EC713772A06B8898|de.swm.mvglive.gwt.client.newsticker.GuiNewstickerService|getNewsticker|1|2|3|4|0|');
     $response = $client->send();
     return $response->getBody();
 }
Esempio n. 9
0
 /**
  * @group ZF-3288
  */
 public function testCustomHttpClientUserAgentIsNotOverridden()
 {
     $this->assertFalse($this->httpClient->getHeader('user-agent'), 'UA is null if no request was made');
     $this->setServerResponseTo(true);
     $this->assertTrue($this->xmlrpcClient->call('method'));
     $this->assertSame('Zend_XmlRpc_Client', $this->httpClient->getHeader('user-agent'), 'If no custom UA is set, set Zend_XmlRpc_Client');
     $expectedUserAgent = 'Zend_XmlRpc_Client (custom)';
     $this->httpClient->setHeaders(array('user-agent' => $expectedUserAgent));
     $this->setServerResponseTo(true);
     $this->assertTrue($this->xmlrpcClient->call('method'));
     $this->assertSame($expectedUserAgent, $this->httpClient->getHeader('user-agent'));
 }
Esempio n. 10
0
 public function testCustomHttpClientUserAgentIsNotOverridden()
 {
     $this->assertFalse($this->httpClient->getHeader('User-Agent'), 'UA is null if no request was made');
     $this->setServerResponseTo(null);
     $this->assertNull($this->jsonClient->call('method'));
     $this->assertSame('Zend_Json_Server_Client', $this->httpClient->getHeader('User-Agent'), 'If no custom UA is set, set Zend_Json_Server_Client');
     $expectedUserAgent = 'Zend_Json_Server_Client (custom)';
     $this->httpClient->setHeaders(array('User-Agent' => $expectedUserAgent));
     $this->setServerResponseTo(null);
     $this->assertNull($this->jsonClient->call('method'));
     $this->assertSame($expectedUserAgent, $this->httpClient->getHeader('User-Agent'));
 }
Esempio n. 11
0
 /**
  * Fetch data from the bug tracker
  * @since Version 3.8.7
  * @param string $url
  * @return array
  */
 public function fetch($url)
 {
     $config = array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => true));
     $client = new Client($url, $config);
     $client->setHeaders(array("X-Redmine-API-Key" => self::REDMINE_API_KEY));
     $response = $client->send();
     $response = $response->getContent();
     if (strlen($response) > 1) {
         $response = json_decode($response, true);
         return $response;
     }
     throw new Exception("Could not fetch current issues from the bug tracker");
 }
 public static function executePost($uri, $value)
 {
     $client = new Client();
     $client->setUri($uri);
     $client->setMethod(Request::METHOD_POST);
     $client->setRawBody($value);
     $client->setHeaders(array('Content-Type: text/plain'));
     $response = $client->send();
     if ($response->getStatusCode() >= 300) {
         throw new \Exception(sprintf('Request Response: Status Code %d, Url: %s', $response->getStatusCode(), $uri));
     }
     return $response->getBody();
 }
 public static function nearby($countryCode, $postalCode)
 {
     $http = new Client();
     $http->setOptions(array('sslverifypeer' => false));
     $headers = new Headers();
     $headers->addHeaderLine('Content-Type', 'application/json');
     $http->setHeaders($headers);
     $http->setUri(self::$apiUrl . 'nearby/' . urlencode($countryCode) . '/' . urlencode($postalCode));
     $http->setMethod('GET');
     $response = $http->send();
     $json = Json::decode($response->getBody());
     return $json;
 }
Esempio n. 14
0
 /**
  * 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();
 }
 public function request($service, array $params = [], $method = 'POST')
 {
     $result = false;
     try {
         $url = sprintf('https://api.superlogica.net/v2/financeiro%s', $service);
         $client = new Client($url);
         $client->setAdapter(new Curl());
         $client->setMethod($method);
         $client->setOptions(['curloptions' => [CURLOPT_HEADER => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false]]);
         $client->setHeaders($this->authHeader);
         if (!empty($params)) {
             if ($method == 'GET') {
                 $client->setParameterGet($params);
             } else {
                 $client->setParameterPost($params);
             }
         }
         $response = $client->send();
         if ($response->isSuccess()) {
             $body = $response->getContent();
             $json = Json\Json::decode($body, 1);
             if (!empty($json[0]['status'])) {
                 if ($json[0]['status'] == '200') {
                     $result = $json;
                 }
             } else {
                 $result = $json;
             }
         }
         $isException = false;
     } catch (\Zend\Http\Exception\RuntimeException $e) {
         $isException = true;
     } catch (\Zend\Http\Client\Adapter\Exception\RuntimeException $e) {
         $isException = true;
     } catch (Json\Exception\RuntimeException $e) {
         $isException = true;
     } catch (Json\Exception\RecursionException $e2) {
         $isException = true;
     } catch (Json\Exception\InvalidArgumentException $e3) {
         $isException = true;
     } catch (Json\Exception\BadMethodCallException $e4) {
         $isException = true;
     }
     if ($isException === true) {
         //código em caso de problemas no decode
     }
     return $result;
 }
Esempio n. 16
0
 public static function getCountries()
 {
     $http = new Client();
     $http->setOptions(array('sslverifypeer' => false));
     $headers = new Headers();
     $headers->addHeaderLine('X-Mashape-Key', MASHAPE_API_KEY);
     $http->setHeaders($headers);
     $http->setUri("https://restcountries-v1.p.mashape.com/all");
     $http->setMethod('GET');
     $response = $http->send();
     $json = Json::decode($response->getBody());
     $data = array();
     foreach ($json as $country) {
         $data[] = array("code" => strtolower($country->alpha2Code), "name" => $country->name);
     }
     return $data;
 }
Esempio n. 17
0
 /**
  * Perform an HTTP request.
  *
  * @param string $baseUrl     Base URL for request
  * @param string $method      HTTP method for request
  * @param string $queryString Query string to append to URL
  * @param array  $headers     HTTP headers to send
  *
  * @throws SerialsSolutions_Summon_Exception
  * @return string             HTTP response body
  */
 protected function httpRequest($baseUrl, $method, $queryString, $headers)
 {
     $this->debugPrint("{$method}: {$baseUrl}?{$queryString}");
     $this->client->resetParameters();
     if ($method == 'GET') {
         $baseUrl .= '?' . $queryString;
     } elseif ($method == 'POST') {
         $this->client->setRawBody($queryString, 'application/x-www-form-urlencoded');
     }
     $this->client->setHeaders($headers);
     // Send Request
     $this->client->setUri($baseUrl);
     $result = $this->client->setMethod($method)->send();
     if (!$result->isSuccess()) {
         throw new SerialsSolutions_Summon_Exception($result->getBody());
     }
     return $result->getBody();
 }
Esempio n. 18
0
 public function curl($url, array $params, $method = "POST")
 {
     $client = new HttpClient();
     $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl');
     $client->setUri($url);
     $client->setOptions(array('maxredirects' => 0, 'timeout' => 30));
     $client->setMethod($method);
     $client->setHeaders(array('username: apiuser', 'password: 123456'));
     //if(!empty($params)) {
     if ($method == "POST" || $method == "PUT" || $method == "DELETE") {
         $client->setParameterPOST($params);
     } else {
         $client->setParameterGET($params);
     }
     //}
     $response = $client->send();
     return $response;
 }
Esempio n. 19
0
 /**
  * Perform an HTTP request.
  *
  * @param string $baseUrl       Base URL for request
  * @param string $method        HTTP method for request (GET,POST, etc.)
  * @param string $queryString   Query string to append to URL
  * @param array  $headers       HTTP headers to send
  * @param string $messageBody   Message body to for HTTP Request
  * @param string $messageFormat Format of request $messageBody and respones
  *
  * @throws EbscoEdsApiException
  * @return string               HTTP response body
  */
 protected function httpRequest($baseUrl, $method, $queryString, $headers, $messageBody = null, $messageFormat = "application/json; charset=utf-8")
 {
     $this->debugPrint("{$method}: {$baseUrl}?{$queryString}");
     $this->client->resetParameters();
     $this->client->setHeaders($headers);
     $this->client->setMethod($method);
     if ($method == 'GET' && !empty($queryString)) {
         $baseUrl .= '?' . $queryString;
     } elseif ($method == 'POST' && isset($messageBody)) {
         $this->client->setRawBody($messageBody);
     }
     $this->client->setUri($baseUrl);
     $this->client->setEncType($messageFormat);
     $result = $this->client->send();
     if (!$result->isSuccess()) {
         throw new \EbscoEdsApiException(json_decode($result->getBody(), true));
     }
     return $result->getBody();
 }
Esempio n. 20
0
 /**
  * @param $endpoint
  * @param $token
  * @param $postArray
  * @return array
  * @throws \Exception
  */
 public function basicOauthPostConnect($endpoint, $token, $postArray)
 {
     $client = new Client($endpoint, ['maxredirects' => 0, 'timeout' => 60]);
     $client->setMethod('POST');
     $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl');
     //to deal with ssl errors
     $client->setHeaders(['content-type' => 'application/json', 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $token]);
     //        $data = array(
     //            $postArray
     //        );
     $json = json_encode($postArray);
     $client->setRawBody($json, 'application/json');
     try {
         $response = $client->send();
     } catch (\Exception $e) {
         throw new \Exception($e);
     }
     $responseObject = json_decode($response->getBody());
     if (is_null($responseObject)) {
         return false;
     }
     $hydrator = new \Zend\Stdlib\Hydrator\ObjectProperty();
     return $hydrator->extract($responseObject);
 }
Esempio n. 21
0
 /**
  * Performs a HTTP request using the specified method
  *
  * @param string $method The HTTP method for the request - 'GET', 'POST',
  *                       'PUT', 'DELETE'
  * @param string $url The URL to which this request is being performed
  * @param array $headers An associative array of HTTP headers
  *                       for this request
  * @param string $body The body of the HTTP request
  * @param string $contentType The value for the content type
  *                                of the request body
  * @param int $remainingRedirects Number of redirects to follow if request
  *                              s results in one
  * @return \Zend\Http\Response The response object
  */
 public function performHttpRequest($method, $url, $headers = null, $body = null, $contentType = null, $remainingRedirects = null)
 {
     if ($remainingRedirects === null) {
         $remainingRedirects = self::getMaxRedirects();
     }
     if ($headers === null) {
         $headers = array();
     }
     // Append a Gdata version header if protocol v2 or higher is in use.
     // (Protocol v1 does not use this header.)
     $major = $this->getMajorProtocolVersion();
     $minor = $this->getMinorProtocolVersion();
     if ($major >= 2) {
         $headers['GData-Version'] = $major + ($minor === null ? '.' + $minor : '');
     }
     // check the overridden method
     if (($method == 'POST' || $method == 'PUT') && $body === null && $headers['x-http-method-override'] != 'DELETE') {
         throw new App\InvalidArgumentException('You must specify the data to post as either a ' . 'string or a child of Zend\\GData\\App\\Entry');
     }
     if ($url === null) {
         throw new App\InvalidArgumentException('You must specify an URI to which to post.');
     }
     $headers['Content-Type'] = $contentType;
     if (self::getGzipEnabled()) {
         // some services require the word 'gzip' to be in the user-agent
         // header in addition to the accept-encoding header
         if (strpos($this->_httpClient->getHeader('User-Agent'), 'gzip') === false) {
             $headers['User-Agent'] = $this->_httpClient->getHeader('User-Agent') . ' (gzip)';
         }
         $headers['Accept-encoding'] = 'gzip, deflate';
     } else {
         $headers['Accept-encoding'] = 'identity';
     }
     // Make sure the HTTP client object is 'clean' before making a request
     // In addition to standard headers to reset via resetParameters(),
     // also reset the Slug and If-Match headers
     $this->_httpClient->resetParameters();
     $this->_httpClient->setHeaders(array('Slug', 'If-Match'));
     // Set the params for the new request to be performed
     $this->_httpClient->setHeaders($headers);
     $urlObj = new \Zend\Uri\Url($url);
     preg_match("/^(.*?)(\\?.*)?\$/", $url, $matches);
     $this->_httpClient->setUri($matches[1]);
     $queryArray = $urlObj->getQueryAsArray();
     foreach ($queryArray as $name => $value) {
         $this->_httpClient->setParameterGet($name, $value);
     }
     $this->_httpClient->setConfig(array('maxredirects' => 0));
     // Set the proper adapter if we are handling a streaming upload
     $usingMimeStream = false;
     $oldHttpAdapter = null;
     if ($body instanceof \Zend\GData\MediaMimeStream) {
         $usingMimeStream = true;
         $this->_httpClient->setRawDataStream($body, $contentType);
         $oldHttpAdapter = $this->_httpClient->getAdapter();
         if ($oldHttpAdapter instanceof \Zend\Http\Client\Adapter\Proxy) {
             $newAdapter = new HttpAdapterStreamingProxy();
         } else {
             $newAdapter = new HttpAdapterStreamingSocket();
         }
         $this->_httpClient->setAdapter($newAdapter);
     } else {
         $this->_httpClient->setRawData($body, $contentType);
     }
     try {
         $response = $this->_httpClient->request($method);
         // reset adapter
         if ($usingMimeStream) {
             $this->_httpClient->setAdapter($oldHttpAdapter);
         }
     } catch (\Zend\Http\Client\Exception $e) {
         // reset adapter
         if ($usingMimeStream) {
             $this->_httpClient->setAdapter($oldHttpAdapter);
         }
         throw new App\HttpException($e->getMessage(), $e);
     }
     if ($response->isRedirect() && $response->getStatus() != '304') {
         if ($remainingRedirects > 0) {
             $newUrl = $response->getHeader('Location');
             $response = $this->performHttpRequest($method, $newUrl, $headers, $body, $contentType, $remainingRedirects);
         } else {
             throw new App\HttpException('Number of redirects exceeds maximum', null, $response);
         }
     }
     if (!$response->isSuccessful()) {
         $exceptionMessage = 'Expected response code 200, got ' . $response->getStatus();
         if (self::getVerboseExceptionMessages()) {
             $exceptionMessage .= "\n" . $response->getBody();
         }
         $exception = new App\HttpException($exceptionMessage);
         $exception->setResponse($response);
         throw $exception;
     }
     return $response;
 }
Esempio n. 22
0
 /**
  * Set date header
  *
  * @param  int|string $value
  * @deprecated Not supported by Twitter since April 08, 2009
  * @return void
  */
 protected function _setDate($value)
 {
     if (is_int($value)) {
         $date = date($this->_dateFormat, $value);
     } else {
         $date = date($this->_dateFormat, strtotime($value));
     }
     $this->_localHttpClient->setHeaders('If-Modified-Since', $date);
 }
Esempio n. 23
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();
 }
Esempio n. 24
0
 /**
  * Store or update an entity in the search index
  *
  * @param  array $data
  * @throws Exception\RuntimeException
  * @throws Exception\IndexException
  * @return boolean true if successfull
  */
 protected function index(array $data)
 {
     $adapter = new Http\Client\Adapter\Curl();
     $adapter->setOptions(array('curloptions' => array(CURLOPT_SSL_VERIFYPEER => false)));
     $client = new Http\Client();
     $client->setAdapter($adapter);
     $client->setMethod('POST');
     $client->setUri($this->getDocumentEndpoint());
     $client->setRawBody(Json::encode($data));
     $client->setHeaders(array('Content-Type' => 'application/json'));
     $response = $client->send();
     if (!$response->isSuccess()) {
         if ($this->throwExceptions) {
             throw new Exception\IndexException("Bad response received from CloudSearch.\n" . $response->toString());
         }
         return false;
     }
     $results = Json::decode($response->getContent(), Json::TYPE_ARRAY);
     $count = $results['adds'] + $results['deletes'];
     return $count != count($data) ? 0 : $count;
 }
Esempio n. 25
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;
 }
Esempio n. 26
0
 /**
  * Test we can get already set headers
  *
  */
 public function testGetHeader()
 {
     $this->_client->setHeaders(array('Accept-encoding' => 'gzip,deflate', 'Accept-language' => 'en,de,*'));
     $this->assertEquals($this->_client->getHeader('Accept-encoding'), 'gzip,deflate', 'Returned value of header is not as expected');
     $this->assertEquals($this->_client->getHeader('X-Fake-Header'), null, 'Non-existing header should not return a value');
 }
 /**
  * Execute/Dispatch the request.
  * @param Client $client
  * @param Request $request
  * @throws \Exception
  * @return \FrontCore\Models\ApiRequestModel
  */
 private function executeRequest(Client $client, $request = NULL)
 {
     //check if api location isset
     if ($this->api_url == "") {
         throw new \Exception(__CLASS__ . " : Line " . __LINE__ . " : Request could not be performed, API Location is not set", 500);
     }
     //end if
     //should session login information be disabled?
     if ($this->api_session_login === TRUE) {
         //load user session data
         $objUserSession = FrontUserSession::isLoggedIn();
         //check if this is a user or site call
         if ($this->api_pword == "" || !$this->api_pword) {
             //try to extract from session
             if (is_object($objUserSession)) {
                 $this->setAPIUserPword($objUserSession->pword);
             }
             //end if
         }
         //end if
         //set api username
         if ($this->api_user == "" || !$this->api_user) {
             //is api key encoded?
             if (is_object($objUserSession)) {
                 if (isset($objUserSession->api_key_encoded) && $objUserSession->api_key_encoded === TRUE) {
                     $key = $this->getServiceLocator()->get("FrontCore\\Models\\FrontCoreSecurityModel")->decodeValue($objUserSession->uname);
                     $this->setAPIUser($key);
                 } else {
                     //try to extract from session
                     $this->setAPIUser($objUserSession->uname);
                 }
                 //end if
             }
             //end if
         }
         //end if
         //set api key
         if ($this->api_key == "" || !$this->api_key) {
             //is api key encoded?
             if (is_object($objUserSession)) {
                 if (isset($objUserSession->api_key_encoded) && $objUserSession->api_key_encoded === TRUE) {
                     $key = $this->getServiceLocator()->get("FrontCore\\Models\\FrontCoreSecurityModel")->decodeValue($objUserSession->api_key);
                     $this->setAPIKey($key);
                 } else {
                     //try to extract from session
                     $this->setAPIKey($objUserSession->api_key);
                 }
                 //end if
             }
             //end if
         }
         //end if
         require "./config/helpers/ob1.php";
         //@TODO - create own api authentication logic
         // throw new \Exception(__CLASS__ . " : Line " . __LINE__ . ": Implement your api request header logic here", 9999);
     } else {
         if ($this->api_key != "") {
             require "./config/helpers/ob2.php";
             //@TODO - create own api authentication logic
             //throw new \Exception(__CLASS__ . " : Line " . __LINE__ . ": Implement your api request header logic here", 9999);
         } else {
             //bypass to perform info request
             $arr_headers = array();
         }
         //end if
     }
     //end if
     //use manually set headers and then clear them
     if (is_array($this->arr_manual_request_headers)) {
         $arr_headers = $this->arr_manual_request_headers;
         $this->arr_manual_request_headers = FALSE;
     }
     //end if
     try {
         //set user logged in flag for submit to api
         if ($objUserSession) {
             $arr_headers["m3userloggedin"] = time();
         }
         //end if
         //set origin url
         $arr_headers['m3originurl'] = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
         //load event manager
         $event = new EventManager();
         //trigger pre event
         $result = $event->trigger("apiCallExecuted.pre", $this, array("objClient" => $client, "objRequest" => $request, 'url' => self::buildURI()));
         //set timeout
         $client->setOptions(array("timeout" => 60, "sslverifypeer" => FALSE));
         if ($request instanceof Request) {
             $client->setHeaders($arr_headers);
             $response = $client->dispatch($request);
         } else {
             $client->setUri(self::buildURI());
             $client->setHeaders($arr_headers);
             $response = $client->send();
         }
         //end if
         $arr_api_data = array("url" => self::buildURI(), "response" => $response->getBody());
         //trigger post event
         $result = $event->trigger("apiCallExecuted.pre", $this, array("objApiData" => (object) $arr_api_data, "objResponse" => $response, "objClient" => $client, "objRequest" => $request, 'url' => self::buildURI()));
         $event->trigger("apiCallExecuted", $this, array("objApiData" => (object) $arr_api_data, "objResponse" => $response));
         //resest the module indicator where set to null
         if (is_null($this->api_module)) {
             $this->api_module = "api";
         }
         //end if
         return self::processResponse($response);
     } catch (\Exception $e) {
         throw new \Exception(__CLASS__ . " : Line " . __LINE__ . " : An error occured performing api request. URL : " . self::buildURI() . " : Error ||" . $e->getMessage(), $e->getCode());
     }
     //end function
 }
Esempio n. 28
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;
 }
Esempio n. 29
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;
 }
Esempio n. 30
0
 /**
  * Perform an http call. This method is used by the resource specific classes. Please use the $payments property to
  * perform operations on payments.
  *
  * @see $payments
  * @see $isuers
  *
  * @param $http_method
  * @param $api_method
  * @param $http_body
  *
  * @return string
  * @throws Mollie_API_Exception
  *
  * @codeCoverageIgnore
  */
 public function performHttpCall($http_method, $api_method, $http_body = NULL)
 {
     if (empty($this->api_key)) {
         throw new Mollie_API_Exception("You have not set an API key. Please use setApiKey() to set the API key.");
     }
     $url = $this->api_endpoint . "/" . self::API_VERSION . "/" . $api_method;
     $adapter = new Zend\Http\Client\Adapter\Socket();
     $client = new Client();
     $client->setAdapter($adapter);
     $client->setUri($this->api_endpoint . "/" . self::API_VERSION . "/" . $api_method);
     $user_agent = join(' ', $this->version_strings);
     $client->setOptions(array('useragent' => $user_agent, 'maxredirects' => 0, 'timeout' => 10, 'verify_peer' => true, 'allow_self_signed' => false, 'sslcafile' => realpath(dirname(__FILE__)) . "/cacert.pem"));
     $client->setMethod($http_method);
     $client->setHeaders(["Accept" => "application/json", "Authorization" => "Bearer {$this->api_key}", "User-Agent" => $user_agent, "Connection" => "Keep-Alive", 'Keep-Alive' => 300, "X-Mollie-Client-Info" => php_uname()]);
     $client->setRawBody($http_body);
     $response = $client->send();
     return $response->getBody();
 }