/**
  * Fetch data from the Marketplace API
  *
  * @param $url
  * @param $method
  * @param null $body
  * @param array $headers
  * @return array|bool
  */
 public function fetch($url, $method, $body = null, $headers = array())
 {
     if (!empty($headers)) {
         $this->httpClient->setDefaultOption('headers', $headers);
     }
     switch ($method) {
         case 'put':
         case 'post':
             $request = $this->httpClient->{$method}($url, $headers, $body);
             break;
         case 'delete':
         case 'get':
             $request = $this->httpClient->{$method}($url, $headers);
             break;
         default:
             return false;
             break;
     }
     try {
         $response = $request->send();
     } catch (\Exception $e) {
         return false;
     }
     return array('status_code' => $response->getStatusCode(), 'body' => $response->json());
 }
 protected function _fetchById($id, $options)
 {
     $settings = craft()->plugins->getPlugin('weather')->getSettings();
     try {
         $client = new Client('http://api.openweathermap.org');
         foreach ($options as $key => $value) {
             $client->setDefaultOption("query/{$key}", $value);
         }
         if (isset($settings->apiKey) && strlen($settings->apiKey) > 0) {
             $client->setDefaultOption('query/APPID', $settings->apiKey);
         }
         $client->setDefaultOption('query/id', $id);
         $request = $client->get('/data/2.5/weather', array('$e'));
         $response = $request->send();
     } catch (CurlException $e) {
         WeatherPlugin::log("Connection error to Open Weather Maps API", LogLevel::Error);
         return false;
     }
     if ($response->isSuccessful()) {
         $data = $response->json();
         if ($data['cod'] == 200) {
             return $data;
         } else {
             WeatherPlugin::log("Error: {$data['message']}", LogLevel::Error);
             return false;
         }
     }
 }
 /**
  * Constructor.
  *
  * @param \stdClass $credentials
  *   An object with the following properties:
  *   - username: Your Browserstack API username.
  *   - password: Your Browserstack API key.
  *
  * @throws \InvalidArgumentException
  */
 function __construct($credentials)
 {
     if (empty($credentials->username) || empty($credentials->password)) {
         throw new \InvalidArgumentException('Username and password parameters are required.');
     }
     $this->client = new \Guzzle\Http\Client('http://www.browserstack.com/screenshots');
     $this->client->setDefaultOption('auth', array($credentials->username, $credentials->password, 'Basic'));
 }
 /**
  * @return Client
  */
 public function getHttpClient()
 {
     if (!$this->client instanceof Client) {
         $this->client = new Client($this->uri);
         $this->client->setDefaultOption('headers/Api-Key', $this->apiKey);
     }
     return $this->client;
 }
 /**
  *
  */
 public function __construct()
 {
     // init the client
     $this->client = new Client();
     $this->client->setDefaultOption('auth', [env('JIRA_USERNAME'), env('JIRA_PASSWORD')]);
     $this->client->setDefaultOption('verify', false);
     $this->parser = new JiraParser(config('jira.BaseUrl'));
 }
 /**
  * Constructor.
  *
  * @param Credentials $credentials The credentials to use.
  */
 public function __construct(Credentials $credentials)
 {
     $this->credentials = $credentials;
     $this->apiUrl = self::ENDPOINT_URL;
     //Initialize API Client
     $this->client = new Client(self::ENDPOINT_URL);
     $this->client->setDefaultOption('auth', array($this->credentials->getEmail(), $this->credentials->getAccountKey(), 'Basic'));
     $this->client->setUserAgent(self::USER_AGENT);
 }
Beispiel #7
0
 /**
  * @param string $apiKey
  * @param string $apiEndpoint
  * @param string $apiVersion
  * @param bool $ssl
  */
 public function __construct($apiKey, $apiEndpoint, $apiVersion, $ssl)
 {
     $this->apiKey = $apiKey;
     $this->mgClient = new Guzzle($this->generateEndpoint($apiEndpoint, $apiVersion, $ssl));
     $this->mgClient->setDefaultOption('curl.options', array('CURLOPT_FORBID_REUSE' => true));
     $this->mgClient->setDefaultOption('auth', array(Api::API_USER, $this->apiKey));
     $this->mgClient->setDefaultOption('exceptions', false);
     $this->mgClient->setUserAgent(Api::SDK_USER_AGENT . '/' . Api::SDK_VERSION);
 }
Beispiel #8
0
 public function setUp()
 {
     parent::setUp();
     $this->client = new Client($this->base_url, array('ssl.certificate_authority' => 'system'));
     $this->xml_client = new Client($this->base_url, array('ssl.certificate_authority' => 'system'));
     $this->client->setDefaultOption('headers/Accept', 'application/json');
     $this->client->setDefaultOption('headers/Content-Type', 'application/json');
     $this->xml_client->setDefaultOption('headers/Accept', 'application/xml');
     $this->xml_client->setDefaultOption('headers/Content-Type', 'application/xml; charset=UTF8');
 }
 public function _initialize()
 {
     $url = trim($this->config['url'], '/') . ':' . $this->config['port'];
     $this->mailcatcher = new \Guzzle\Http\Client($url);
     if (isset($this->config['guzzleRequestOptions'])) {
         foreach ($this->config['guzzleRequestOptions'] as $option => $value) {
             $this->mailcatcher->setDefaultOption($option, $value);
         }
     }
 }
 public function client()
 {
     if ($this->client) {
         return $this->client;
     }
     $this->client = new Client($this->apiUrl);
     $this->client->setDefaultOption('headers/Accept', 'application/json');
     $this->client->setDefaultOption('headers/Content-Type', 'application/json');
     $this->authenticate();
     return $this->client;
 }
Beispiel #11
0
    public function setUp() {
        parent::setUp();
        $this->client = new Client($this->base_url);
        $this->xml_client = new Client($this->base_url);

        $this->client->setDefaultOption('headers/Accept', 'application/json');
        $this->client->setDefaultOption('headers/Content-Type', 'application/json');

        $this->xml_client->setDefaultOption('headers/Accept', 'application/xml');
        $this->xml_client->setDefaultOption('headers/Content-Type', 'application/xml; charset=UTF8');
    }
Beispiel #12
0
 /**
  * @param $uri
  * @param $username
  * @param $password
  */
 public function __construct($uri, $username = "", $password = "")
 {
     error_log("{$username} {$password}");
     $this->uri = $uri;
     $this->username = $username;
     $this->password = $password;
     $this->logger = new \Psr\Log\NullLogger();
     $client = new Http\Client($uri);
     $client->setDefaultOption('auth', array($username, $password, 'Basic'));
     $client->setDefaultOption('timeout', 5);
     $client->setDefaultOption('connect_timeout', 1);
     $this->setClient($client);
 }
 /**
  * Makes the request to the server.
  * 
  * @param string $server	
  * @param string $service		The rest service to access e.g. /connections/communities/all
  * @param string $method		GET, POST or PUT
  * @param string $body
  * @param string $headers
  */
 public function makeRequest($server, $service, $method, $options, $body = null, $headers = null, $endpointName = "connections")
 {
     $store = SBTCredentialStore::getInstance();
     $settings = new SBTSettings();
     $token = $store->getToken($endpointName);
     $response = null;
     $client = new Client($server);
     $client->setDefaultOption('verify', false);
     // If global username and password is set, then use it; otherwise use user-specific credentials
     if ($settings->getBasicAuthMethod($endpointName) == 'global') {
         $user = $settings->getBasicAuthUsername($endpointName);
         $password = $settings->getBasicAuthPassword($endpointName);
     } else {
         $user = $store->getBasicAuthUsername($endpointName);
         $password = $store->getBasicAuthPassword($endpointName);
     }
     try {
         $request = $client->createRequest($method, $service, $headers, $body, $options);
         if ($settings->forceSSLTrust($endpointName)) {
             $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
             $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
         }
         if ($method == 'POST' && isset($_FILES['file']['tmp_name'])) {
             $request->addPostFile('file', $_FILES['file']['tmp_name']);
         }
         $request->setAuth($user, $password);
         $response = $request->send();
     } catch (Guzzle\Http\Exception\BadResponseException $e) {
         $response = $e->getResponse();
     }
     return $response;
 }
Beispiel #14
0
 public function run($data, $ips)
 {
     if ($data && $ips and is_array($ips)) {
         foreach ($ips as $ip) {
             $client = new Client('http://' . $ip);
             $client->setDefaultOption('headers', ['Content-type' => 'application/json']);
             $client->setDefaultOption('exceptions', false);
             $client->setDefaultOption('timeout', 20);
             $client->setDefaultOption('connecttimeout', 0);
             $client->setDefaultOption('debug', false);
             $request = $client->post("/", [], []);
             $request->setBody($data);
             $request->send();
         }
     }
 }
Beispiel #15
0
 public static function buildRequestD($pageId, $act, $servlet, $timeStamp)
 {
     ValidateFunc::checkNotNull($pageId, "Page id can't be null");
     $client = new Client(CommonInfo::$DOMAIN . $servlet);
     $params = array(CommonInfo::$URL_ACT => $act, CommonInfo::$URL_PAGEID => $pageId, CommonInfo::$URL_TIMESTAMP => $timeStamp);
     $client->setDefaultOption('query', $params);
     return $client;
 }
Beispiel #16
0
 /**
  * Setup the guzzle client
  *
  * @version 1.0
  * @since   1.0
  * @author  Daniel Noel-Davies
  *
  * @param   string  $url       Api URL
  *
  * @return  Object
  */
 public static function setupClient($url)
 {
     // Initiate the client with the API url
     $client = new Guzzle\Http\Client(Config::get('TrafficLive::api_url'));
     // Setup the basic authentication to Traffic Live
     $client->setDefaultOption('auth', array(Config::get('TrafficLive::api_email'), Config::get('TrafficLive::api_token'), 'Basic'));
     return $client->get($url);
 }
Beispiel #17
0
 public static function addDebugOptionsToHttpClient(Client $guzzleClient)
 {
     $guzzleClient->setDefaultOption('debug', true);
     $echoCb = function (Event $event) {
         echo (string) $event['request'] . PHP_EOL;
         echo (string) $event['response'] . PHP_EOL;
     };
     $guzzleClient->getEventDispatcher()->addListener('request.complete', $echoCb);
     $guzzleClient->getEventDispatcher()->addListener('request.exception', $echoCb);
 }
Beispiel #18
0
 /**     *
  * @param \Guzzle\Http\Client $client
  * @param JiraParser $parser
  * @param string $baseUrl
  * @param string $username
  * @param string $password
  */
 public function __construct(Client $client, JiraParser $parser, $baseUrl, $username, $password)
 {
     // init the client
     $this->client = new Client();
     $this->client->setDefaultOption('auth', array($username, $password));
     $this->client->setDefaultOption('verify', false);
     $this->parser = $parser;
     $this->baseUrl = $baseUrl;
     $this->username = $username;
     $this->password = $password;
 }
Beispiel #19
0
 /**
  * Register Guzzle Clients
  *
  * @param Application $app
  *
  * @return Guzzle\Http\Client
  */
 public function register(Application $app)
 {
     $app['guzzle.client.read'] = $app->protect(function () use($app) {
         $client = new GuzzleClient();
         $client->setDefaultOption('auth', array($app['guzzle.client.read.user'], $app['guzzle.client.read.pass']));
         return $client;
     });
     $app['guzzle.client.write'] = $app->protect(function () use($app) {
         $client = new GuzzleClient();
         $client->setDefaultOption('auth', array($app['guzzle.client.write.user'], $app['guzzle.client.write.pass']));
         return $client;
     });
 }
Beispiel #20
0
 /**
  * @param LoggerInterface       $logger
  * @param Client                $client
  * @param UrlGeneratorInterface $router
  * @param CsrfProviderInterface $csrfProvider
  */
 public function __construct(LoggerInterface $logger, Client $client, Discover $discover, Import $import, UrlGeneratorInterface $router, CsrfProviderInterface $csrfProvider, $oauthClientId, $oauthClientSecret)
 {
     $client->setDefaultOption('headers/Accept', 'application/vnd.github.v3');
     $import->setProvider($this);
     $this->client = $client;
     $this->discover = $discover;
     $this->import = $import;
     $this->csrfProvider = $csrfProvider;
     $this->oauthClientId = $oauthClientId;
     $this->oauthClientSecret = $oauthClientSecret;
     $this->authorizeUrl = '/login/oauth/authorize';
     parent::__construct($logger, $router);
 }
Beispiel #21
0
 /**
  * 
  * @param LosConnection $losConnection
  * @param \Twig_Environment $twig
  * @param ContainerInterface $container
  */
 public function __construct(LosConnection $losConnection, \Twig_Environment $twig, ContainerInterface $container)
 {
     $this->losConnection = $losConnection;
     $serviceUrl = $losConnection->getServiceUrl();
     if (!isset($serviceUrl)) {
         $serviceUrl = $this::DEFAULT_SERVICE_URL;
     }
     $this->client = new Client($serviceUrl, array('ssl.certificate_authority' => false));
     $this->twig = $twig;
     $this->em = $container->get('doctrine')->getEntityManager();
     $this->container = $container;
     $this->client->setDefaultOption('auth', array($this::USERNAME, $this::PASSWORD, 'Basic'));
     $this->user = array('AuthUser' => array('uri' => $losConnection->getHost(), 'username' => $losConnection->getUsername(), 'password' => $losConnection->getPassword()), 'lostype' => 0, 'apiKey' => $losConnection->getLicenseKey());
     $this->logger = $this->container->get('logger');
 }
 /**
  * The callback function for authenticating the user and then storing the token in the CredentialStore (no content
  * is being requested).
  */
 public function authenticationCallback()
 {
     if (!isset($_GET['code'])) {
         return;
     }
     $store = SBTCredentialStore::getInstance();
     $settings = new SBTSettings();
     $endpointName = "connections";
     if (isset($_GET['endpointName'])) {
         $endpointName = $_GET['endpointName'];
     }
     $parameters = array('callback_uri' => $settings->getOAuth2CallbackURL($endpointName), 'code' => $_GET['code'], 'grant_type' => 'authorization_code', 'client_id' => $settings->getClientId($endpointName), 'client_secret' => $settings->getClientSecret($endpointName));
     $tokenURL = $settings->getAccessTokenURL($endpointName) . '?' . http_build_query($parameters, null, '&');
     $client = new Client($tokenURL);
     $client->setDefaultOption('verify', false);
     $headers = null;
     $body = null;
     $options = array();
     $response = null;
     try {
         $request = $client->createRequest('GET', $tokenURL, $headers, $body, $options);
         if ($settings->forceSSLTrust($endpointName)) {
             $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
             $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
         }
         $response = $request->send();
         foreach ($response->getHeaderLines() as $h) {
             if (strpos($h, "Content-Type") === 0) {
                 header($h, TRUE);
             }
         }
         header(':', true, $response->getStatusCode());
         header('X-PHP-Response-Code: ' . $response->getStatusCode(), true, $response->getStatusCode());
         parse_str($response->getBody(TRUE), $info);
         if (!isset($info['access_token'])) {
             die('Missing access token. Something went wrong - make sure that your client ID and client secret are correct and try again.');
         }
         $accessToken = $store->getOAuthAccessToken($endpointName);
         if ($accessToken == null || $accessToken == "") {
             $store->storeOAuthAccessToken($info['access_token'], $endpointName);
         }
         header("Location: " . $settings->getOAuthOrigin($endpointName));
     } catch (Guzzle\Http\Exception\BadResponseException $e) {
         $response = $e->getResponse();
         print_r($response->getBody(TRUE));
     }
 }
 /**
  * Get HTTP browser
  *
  * @param \Guzzle\Http\Client
  */
 protected function getBrowser()
 {
     if (!$this->browser instanceof Client) {
         $this->browser = new Client($this->host);
         // try to set User-Agent from original request
         $user_agent = self::DEFAULT_USER_AGENT;
         if ($this->request) {
             $user_agent = $this->request->server->get('HTTP_USER_AGENT', self::DEFAULT_USER_AGENT);
         }
         $this->browser->setDefaultHeaders(['User-Agent' => $user_agent]);
         // configure browser client
         $this->browser->setDefaultOption('timeout', $this->timeout);
         if ($this->proxy_list) {
             $this->browser->setDefaultOption('proxy', $this->proxy_list[array_rand($this->proxy_list)]);
         }
     }
     return $this->browser;
 }
 /**
  * Send a request to the API
  * @param string $method HTTP request method
  * @param string $url the relative URL of the desired endpoint
  * @param array $queryParams optional query string parameters
  * @param array $data request body data
  * @return array
  * @throws ApiException
  */
 protected function request($method, $url, $queryParams = array(), $data = array())
 {
     $client = new Client(self::BASE_URL);
     $client->setDefaultOption("auth", array($this->key, $this->secret, "Basic"));
     $headers = array("accept" => "application/json", "content-type" => "application/json");
     $request = $client->createRequest($method, $url, $headers, json_encode($data));
     // Add query string parameters to the request
     foreach ($queryParams as $key => $value) {
         $request->getQuery()->set($key, $value);
     }
     try {
         $response = $request->send();
         $responseBody = json_decode($response->getBody(true), true);
     } catch (ClientErrorResponseException $e) {
         $responseBody = json_decode($e->getResponse()->getBody(true), true);
         throw new ApiException($e->getResponse()->getStatusCode(), $responseBody['error']);
     }
     return $responseBody;
 }
Beispiel #25
0
 /**
  * @param string $method HTTP method
  * @param string $url
  * @param string $deserializeTo
  * @param array|object $body
  * @param array $params querystring parameters
  * @throws StripeException
  * @return mixed
  */
 public function request($method, $url, $deserializeTo = null, $body = null, array $params = array())
 {
     $baseUrl = self::BASE_URL . '/' . self::VERSION . '/';
     $client = new GuzzleClient($baseUrl);
     $client->setDefaultOption("auth", array($this->apiKey, '', "Basic"));
     $serializer = SerializerBuilder::create()->build();
     if (!is_null($body)) {
         $body = json_decode($serializer->serialize($body, 'json'), true);
         $body = $this->convertBooleans($body);
     }
     $request = $client->createRequest($method, $url, null, $body);
     foreach ($params as $key => $value) {
         if (is_bool($value)) {
             if ($value) {
                 $value = 'true';
             } else {
                 $value = 'false';
             }
         }
         if (!is_null($value)) {
             $request->getQuery()->set($key, $value);
         }
     }
     try {
         $response = $request->send();
     } catch (ClientErrorResponseException $e) {
         $responseBody = json_decode($e->getResponse()->getBody(true), true);
         $responseBody = $responseBody['error'];
         $code = array_key_exists('code', $responseBody) ? $responseBody['code'] : null;
         $param = array_key_exists('param', $responseBody) ? $responseBody['param'] : null;
         throw new StripeException($responseBody['message'], $e->getResponse()->getStatusCode(), $responseBody['type'], $code, $param, $e);
     }
     if (is_null($deserializeTo)) {
         $responseBody = json_decode($response->getBody(true), true);
     } else {
         $responseBody = $serializer->deserialize($response->getBody(true), $deserializeTo, 'json');
     }
     return $responseBody;
 }
 public static function destroyData(Event $event)
 {
     $io = $event->getIO();
     if (!$event->isDevMode()) {
         $io->write('This script is only supported in development mode. Exiting.');
         return;
     }
     $destroy_data = $io->askConfirmation('<options=bold>Are you sure you want to destroy all local data? [y,N]: </>', false);
     if (true === $destroy_data) {
         $client = new Client();
         $client->setDefaultOption('exceptions', false);
         $es_indices = self::DEFAULT_PROJECT_NAME . '.*';
         $couch_event_db = self::DEFAULT_PROJECT_NAME . '%2Bdomain_events';
         $couch_process_db = self::DEFAULT_PROJECT_NAME . '%2Bprocess_states';
         $io->write('-> deleting Elasticsearch indices "' . $es_indices . '"');
         $client->delete('http://localhost:9200/' . $es_indices)->send();
         $io->write('-> deleting CouchDb database "' . $couch_event_db . '"');
         $client->delete('http://127.0.0.1:5984/' . $couch_event_db)->send();
         $io->write('-> deleting CouchDb database "' . $couch_process_db . '"');
         $client->delete('http://127.0.0.1:5984/' . $couch_process_db)->send();
     }
     return $destroy_data;
 }
Beispiel #27
0
 * The OAUTH_TOKEN environment variable is required.
 *
 *     Usage: php gh-release.php X.Y.Z
 */
require __DIR__ . '/../vendor/autoload.php';
use Guzzle\Http\Client;
use Guzzle\Http\Url;
use Guzzle\Stream;
$owner = 'davidtsadler';
$repo = 'ebay-sdk-trading';
$token = getenv('OAUTH_TOKEN') or die('An OAUTH_TOKEN environment variable is required');
isset($argv[1]) or die('Usage php gh-release.php X.Y.Z');
$tag = $argv[1];
assert(file_exists(__DIR__ . '/artifacts/dts-trading.zip'));
assert(file_exists(__DIR__ . '/artifacts/dts-trading.phar'));
// Grab and validate the tag annotation
chdir(dirname(__DIR__));
$message = `chag contents --tag "{$tag}"` or die('Chag could not find or parse the tag');
// Create a GitHub client.
$client = new Client('https://api.github.com/');
$client->setDefaultOption('headers/Authorization', "token {$token}");
// Create the release
$response = $client->post("repos/{$owner}/{$repo}/releases", array('Content-Type' => 'application/json'), json_encode(array('tag_name' => $tag, 'name' => "Version {$tag}", 'body' => $message, 'prerelease' => false)))->send();
// Grab the location of the new release
$url = (string) $response->getHeader('Location');
// Uploads go to uploads.github.com
$uploadUrl = Url::factory($url);
$uploadUrl->setHost('uploads.github.com');
$client->post($uploadUrl . '/assets?name=dts-trading.zip', array('Content-Type' => 'application/zip'), fopen(__DIR__ . '/artifacts/dts-trading.zip', 'r'))->send();
$client->post($uploadUrl . '/assets?name=dts-trading.phar', array('Content-Type' => 'application/phar'), fopen(__DIR__ . '/artifacts/dts-trading.phar', 'r'))->send();
echo "Release successfully published to: {$url}\n";
Beispiel #28
0
<?php

// Guzzle v3 — our PHP is too old to do latest version
// https://guzzle3.readthedocs.org/docs.html
require 'vendor/autoload.php';
use Guzzle\Http\Client;
// constants
define('VAULT_URL', 'https://vault.cca.edu');
define('SEARCH_API', '/api/search');
// disable SSL validation since our cert causes an error
$client = new Client(VAULT_URL, array('ssl.certificate_authority' => false));
// OAuth token for this specific app, client credentials grant from "eric1"
// that account has privileges to see all items in Syllabus Collection
$token = getenv("SYLLABI_API_TOKEN");
$client->setDefaultOption('headers/X-Authorization', 'access_token=' . $token);
// construct query string for EQUELLA search API
// parse_str parses a query string into variables inside $arr
if (isset($_SERVER['QUERY_STRING'])) {
    parse_str($_SERVER['QUERY_STRING'], $options);
} else {
    $options = array();
}
$options['info'] = 'metadata,basic,attachment';
// search only the Syllabus Collection (this is its UUID)
$options['collections'] = '9ec74523-e018-4e01-ab4e-be4dd06cdd68';
// translate "semester" parameter into XML where query
if (isset($options['semester'])) {
    $semester = $options['semester'];
    unset($options['semester']);
    $options['where'] = "/xml/local/courseInfo/semester = '" . $semester . "'";
}
 public function __construct(Client $client = null)
 {
     $this->client = $client ?: new Client();
     $this->client->setDefaultOption('headers', ['accept' => self::DEFAULT_MIME_TYPE]);
     $this->client->setUserAgent(self::DEFAULT_USER_AGENT);
 }
 /**
  * @param string $token
  *
  * @return $this
  */
 public function setToken($token)
 {
     $this->token = $token;
     $this->client->setDefaultOption('headers/Authorization', 'Bearer ' . $this->token);
     return $this;
 }