/**
  * @param $timeout
  */
 public function __construct($timeout, $logger)
 {
     $this->browser = new Browser(new Curl());
     $this->browser->getClient()->setVerifyPeer(false);
     $this->browser->getClient()->setTimeout($timeout);
     $this->logger = $logger;
 }
Esempio n. 2
0
 /**
  * @param array $data
  *
  * @return array|string|null
  *
  * @throws \Exception
  */
 public function send($data = null)
 {
     $request = new FormRequest($this->method, $this->resource, $this->host);
     if ($data) {
         $request->addFields($data);
     }
     try {
         $this->logger->addDebug('Request: ' . $request->getUrl());
         /** @var Buzz\Message\Response $response */
         $response = $this->client->send($request);
         $this->logger->addDebug('Response: ' . $response->getStatusCode() . ' ' . substr($response->getContent(), 0, 300) . PHP_EOL . var_export($this->client->getClient()->getInfo(), true));
     } catch (\Exception $e) {
         switch ($e->getCode()) {
             case 28:
                 $code = 504;
                 break;
             default:
                 $code = $e->getCode() >= 100 ? $e->getCode() : 500;
         }
         $this->logger->addCritical(PHP_EOL . __METHOD__ . sprintf('[%s/%s] %s', $e->getCode(), $code, $e->getMessage()));
         throw new WebGateException($e->getMessage(), $code, $e);
     }
     if ($response->getStatusCode() != 200) {
         throw new WebGateException(json_decode($response->getContent(), true), $response->getStatusCode());
     }
     return json_decode($response->getContent(), true);
 }
 /**
  * Sends the data to the given registration IDs via the GCM server
  *
  * @param  \RMS\PushNotificationsBundle\Message\MessageInterface              $message
  * @throws \RMS\PushNotificationsBundle\Exception\InvalidMessageTypeException
  * @return bool
  */
 public function send(MessageInterface $message)
 {
     if (!$message instanceof AndroidMessage) {
         throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by GCM", get_class($message)));
     }
     if (!$message->isGCM()) {
         throw new InvalidMessageTypeException("Non-GCM messages not supported by the Android GCM sender");
     }
     $headers = array("Authorization: key=" . $this->apiKey, "Content-Type: application/json");
     $data = array_merge($message->getGCMOptions(), array("data" => $message->getData()));
     // Chunk number of registration IDs according to the maximum allowed by GCM
     $chunks = array_chunk($message->getGCMIdentifiers(), $this->registrationIdMaxCount);
     // Perform the calls (in parallel)
     $this->responses = array();
     foreach ($chunks as $registrationIDs) {
         $data["registration_ids"] = $registrationIDs;
         $this->responses[] = $this->browser->post($this->apiURL, $headers, json_encode($data));
     }
     // If we're using multiple concurrent connections via MultiCurl
     // then we should flush all requests
     if ($this->browser->getClient() instanceof MultiCurl) {
         $this->browser->getClient()->flush();
     }
     // Determine success
     foreach ($this->responses as $response) {
         $message = json_decode($response->getContent());
         if ($message === null || $message->success == 0 || $message->failure > 0) {
             return false;
         }
     }
     return true;
 }
Esempio n. 4
0
 /**
  * Class constructor.
  *
  * @param $apiKey
  * @param null $apiUrl
  */
 public function __construct($apiKey, $apiUrl = null)
 {
     $this->apiKey = $apiKey;
     if ($apiUrl) {
         $this->apiUrl = $apiUrl;
     }
     $this->browser = new Browser(new MultiCurl());
     $this->browser->getClient()->setVerifyPeer(false);
 }
 /**
  * @param array $options
  */
 public function __construct(array $options = [])
 {
     $this->options = array_merge(static::getDefaultConfigs(), $options);
     $buzzClassName = $this->options['buzz.class'];
     $this->buzz = new $buzzClassName();
     $this->servers = $this->options['replay.http_client.servers'];
     // Increase timeout
     $this->buzz->getClient()->setTimeout($this->options['buzz.timeout']);
 }
 /**
  * Execute an Api request
  *
  * @param string $endpoint
  * @param array $payload
  * @param array $options
  * @return mixed
  */
 public function execute($endpoint, array $payload, array $options = [])
 {
     $endpoint = $this->baseEndpoint . $endpoint;
     // set a timeout if applicable
     if (isset($options['timeout'])) {
         $this->transport->getClient()->setTimeout((int) $options['timeout']);
     } else {
         if (isset($this->timeout)) {
             $this->transport->getClient()->setTimeout((int) $this->timeout);
         }
     }
     $response = $this->transport->post($endpoint, $this->getHeaders(), json_encode(['meta' => ['when' => date('Y-m-d H:i:s'), 'server' => gethostname()], 'data' => $payload]));
     return json_decode($response->getContent(), true);
 }
Esempio n. 7
0
 /**
  * Instantiated a new http client
  *
  * @param array        $options Http client options
  * @param null|Browser $browser Buzz client
  */
 public function __construct(array $options = array(), Browser $browser = null)
 {
     $this->options = array_merge($this->options, $options);
     $this->browser = $browser ?: new Browser(new Curl());
     $this->browser->getClient()->setTimeout($this->options['timeout']);
     $this->browser->getClient()->setVerifyPeer(false);
     if (null !== $this->options['login'] || null !== $this->options['token']) {
         if (null !== $this->options['token']) {
             $options = array($this->options['token']);
         } else {
             $options = array($this->options['login'], $this->options['password']);
         }
         $this->browser->addListener(new AuthListener($this->options['auth_method'], $options));
     }
 }
Esempio n. 8
0
 /**
  * Flush notifications. Triggers the requests.
  *
  * @return array|bool If there are no errors, return true.
  *                    If there were no notifications in the queue, return false.
  *                    Else return an array of information for each notification sent (success, statusCode, headers, content)
  *
  * @throws \ErrorException
  */
 public function flush()
 {
     if (empty($this->notifications)) {
         return false;
     }
     // for each endpoint server type
     $responses = $this->prepareAndSend($this->notifications);
     // if multi curl, flush
     if ($this->browser->getClient() instanceof MultiCurl) {
         /** @var MultiCurl $multiCurl */
         $multiCurl = $this->browser->getClient();
         $multiCurl->flush();
     }
     /** @var Response|null $response */
     $return = array();
     $completeSuccess = true;
     foreach ($responses as $i => $response) {
         if (!isset($response)) {
             $return[] = array('success' => false, 'endpoint' => $this->notifications[$i]->getEndpoint());
             $completeSuccess = false;
         } elseif (!$response->isSuccessful()) {
             $return[] = array('success' => false, 'endpoint' => $this->notifications[$i]->getEndpoint(), 'statusCode' => $response->getStatusCode(), 'headers' => $response->getHeaders(), 'content' => $response->getContent(), 'expired' => in_array($response->getStatusCode(), array(400, 404, 410)));
             $completeSuccess = false;
         } else {
             $return[] = array('success' => true);
         }
     }
     // reset queue
     $this->notifications = null;
     return $completeSuccess ? true : $return;
 }
Esempio n. 9
0
 /**
  * @param string $url
  *   The URL to POST to
  * @param SiteDocument $site
  *   The site being posted to
  * @param array $params
  *   An array of keys and values to be posted
  *
  * @return mixed
  *   The content of the response
  *
  * @throws WardenRequestException
  *   If any error occurs
  */
 public function post($url, SiteDocument $site, array $params = array())
 {
     try {
         $this->setClientTimeout($this->connectionTimeout);
         // Don't verify SSL certificate.
         // @TODO make this optional
         $this->buzz->getClient()->setVerifyPeer(FALSE);
         if ($site->getAuthUser() && $site->getAuthPass()) {
             $headers = array(sprintf('Authorization: Basic %s', base64_encode($site->getAuthUser() . ':' . $site->getAuthPass())));
             $this->setConnectionHeaders($headers);
         }
         $params['token'] = $this->sslEncryptionService->generateRequestToken();
         $content = http_build_query($params);
         /** @var \Buzz\Message\Response $response */
         $response = $this->buzz->post($url, $this->connectionHeaders, $content);
         if (!$response->isSuccessful()) {
             $this->logger->addError("Unable to request data from {$url}\nStatus code: " . $response->getStatusCode() . "\nHeaders: " . print_r($response->getHeaders(), TRUE));
             throw new WardenRequestException("Unable to request data from {$url}. Check log for details.");
         }
         $site->setLastSuccessfulRequest();
         $this->siteManager->updateDocument();
         return $response->getContent();
     } catch (ClientException $clientException) {
         throw new WardenRequestException($clientException->getMessage());
     }
 }
 /**
  * Calls an HTTP POST function to verify if the user's guess was correct
  *
  * @param string $remoteIp
  * @param string $challenge
  * @param string $response
  * @throws Exception
  * @return boolean
  */
 public function checkAnswer($remoteIp, $challenge, $response)
 {
     $headers = array('Connection' => 'close');
     $content = array('private_key' => $this->privateKey, 'session_token' => $response, 'simple_mode' => 1);
     $browser = new Browser();
     $browser->getClient()->setVerifyPeer(false);
     try {
         /** @var Response $resp */
         $resp = $browser->post(self::VERIFY_SERVER, $headers, http_build_query($content));
     } catch (Exception $e) {
         throw new CaptchaException('Failed to send captcha', 500, $e);
     }
     if (!$resp->isSuccessful()) {
         throw new CaptchaException('Error: ' . $resp->getStatusCode());
     }
     $answer = $resp->getContent();
     if (!$answer) {
         throw new CaptchaException('Error: Invalid captcha response');
     }
     $success = isset($answer) && filter_var($answer, FILTER_VALIDATE_INT);
     if (!$success) {
         return new CaptchaResponse($success, 'Invalid captcha');
     }
     return new CaptchaResponse($success);
 }
 /**
  * Calls an HTTP POST function to verify if the user's guess was correct
  *
  * @param string $remoteIp
  * @param string $challenge
  * @param string $response
  * @throws Exception
  * @return boolean
  */
 public function checkAnswer($remoteIp, $challenge, $response)
 {
     if (empty($remoteIp)) {
         throw new CaptchaException('RemoteIp missing');
     }
     $headers = array('Connection' => 'close');
     $content = array('secret' => $this->privateKey, 'remoteip' => $remoteIp, 'response' => $response);
     $browser = new Browser();
     $browser->getClient()->setVerifyPeer(false);
     try {
         /** @var Response $resp */
         $resp = $browser->post(self::VERIFY_SERVER, $headers, http_build_query($content));
     } catch (Exception $e) {
         throw new CaptchaException('Failed to check captcha', 500, $e);
     }
     if (!$resp->isSuccessful()) {
         throw new CaptchaException('Error: ' . $resp->getStatusCode());
     }
     $answer = json_decode($resp->getContent());
     if (!$answer) {
         throw new CaptchaException('Error: Invalid captcha response');
     }
     $success = isset($answer->success) && filter_var($answer->success, FILTER_VALIDATE_BOOLEAN);
     if (!$success) {
         return new CaptchaResponse($success, 'Invalid captcha');
     }
     return new CaptchaResponse($success);
 }
Esempio n. 12
0
 /**
  * {@inheritdoc}
  */
 protected function sendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $this->browser->getClient()->setTimeout($this->getConfiguration()->getTimeout());
     $this->browser->getClient()->setMaxRedirects(0);
     $request = $this->browser->getMessageFactory()->createRequest($internalRequest->getMethod(), $uri = (string) $internalRequest->getUri());
     $request->setProtocolVersion($internalRequest->getProtocolVersion());
     $request->setHeaders($this->prepareHeaders($internalRequest, false));
     $data = $this->browser->getClient() instanceof AbstractCurl ? $this->prepareContent($internalRequest) : $this->prepareBody($internalRequest);
     $request->setContent($data);
     try {
         $response = $this->browser->send($request);
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUri($uri, $this->getName(), $e->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse($response->getStatusCode(), (string) $response->getProtocolVersion(), HeadersNormalizer::normalize($response->getHeaders()), BodyNormalizer::normalize($response->getContent(), $internalRequest->getMethod()));
 }
Esempio n. 13
0
 /**
  * Mockable constructor.
  * @param Browser $browser Buzz instance
  * @param array $options
  */
 public function __construct(Browser $browser, array $options)
 {
     if ($browser->getClient() instanceof FileGetContents) {
         throw new \InvalidArgumentException('The FileGetContents client is known not to work with this library. Please instantiate the Browser with an instance of \\Buzz\\Client\\Curl');
     }
     $this->browser = $browser;
     $this->options = $options;
 }
Esempio n. 14
0
 /**
  * Sends a request.
  *
  * @param string $url     The url.
  * @param string $method  The http method.
  * @param array  $headers The header.
  * @param array  $content The content.
  *
  * @throws \Widop\HttpAdapter\HttpAdapterException If an error occured.
  *
  * @return \Widop\HttpAdapter\HttpResponse The response.
  */
 private function sendRequest($url, $method, array $headers = array(), array $content = array())
 {
     $this->browser->getClient()->setMaxRedirects($this->getMaxRedirects());
     try {
         $response = $this->browser->call($url, $method, $headers, $content);
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage());
     }
     return $this->createResponse($response->getStatusCode(), $url, $response->getHeaders(), $response->getContent());
 }
Esempio n. 15
0
 /**
  * @param Browser $browser
  */
 public function setBrowser(Browser $browser)
 {
     $client = $browser->getClient();
     $client->setVerifyPeer(false);
     $client->setTimeout(30);
     if ($client instanceof \Buzz\Client\Curl) {
         $client->setOption(CURLOPT_USERAGENT, 'KnpBundles.com Bot');
     }
     $this->browser = $browser;
 }
Esempio n. 16
0
 /**
  * Purges all content elements currently in cache.
  *
  * @return void
  */
 public function purgeAll()
 {
     foreach ($this->purgeServers as $server) {
         $this->prepareUserAuth($server);
         $this->httpBrowser->call($server, 'PURGE', array('X-Location-Id' => '*'));
         $client = $this->httpBrowser->getClient();
         if ($client instanceof BatchClientInterface) {
             $client->flush();
         }
     }
 }
Esempio n. 17
0
 /**
  * Sends the data to the given registration ID's via the GCM server.
  *
  * @param mixed $data
  * @param array $registrationIds
  * @param array $options         to add along with message, such as collapse_key, time_to_live, delay_while_idle
  *
  * @return bool
  */
 public function send($data, array $registrationIds, array $options = array())
 {
     $headers = array('Authorization: key=' . $this->apiKey, 'Content-Type: application/json');
     $data = array_merge($options, array('data' => $data));
     // Chunk number of registration ID's according to the maximum allowed by GCM
     $chunks = array_chunk($registrationIds, $this->registrationIdMaxCount);
     // Perform the calls (in parallel)
     $this->responses = array();
     foreach ($chunks as $registrationIds) {
         $data['registration_ids'] = $registrationIds;
         $this->responses[] = $this->browser->post($this->apiUrl, $headers, json_encode($data));
     }
     $this->browser->getClient()->flush();
     // Determine success
     foreach ($this->responses as $response) {
         $message = json_decode($response->getContent());
         if ($message === null || $message->success == 0 || $message->failure > 0) {
             return false;
         }
     }
     return true;
 }
 /**
  * Gets a valid authentication token
  *
  * @return bool
  */
 protected function getAuthToken()
 {
     $data = array("Email" => $this->username, "Passwd" => $this->password, "accountType" => "HOSTED_OR_GOOGLE", "source" => $this->source, "service" => "ac2dm");
     $buzz = new Browser();
     $buzz->getClient()->setVerifyPeer(false);
     $response = $buzz->post("https://www.google.com/accounts/ClientLogin", array(), http_build_query($data));
     if ($response->getStatusCode() !== 200) {
         return false;
     }
     preg_match("/Auth=([a-z0-9_\\-]+)/i", $response->getContent(), $matches);
     $this->authToken = $matches[1];
     return true;
 }
 public function send($address, $amount, $ip, $referral = false)
 {
     $apiKey = $this->settingRepository->getApiKey();
     $query = http_build_query(array('apikey' => $apiKey));
     $url = $this->config['api_url'] . '?' . $query;
     $headers = array('Connection' => 'close');
     $data = http_build_query(array('address' => $address, 'amount' => $amount, 'referral' => $referral, 'ip' => $ip));
     $browser = new Browser();
     $browser->getClient()->setVerifyPeer(false);
     /** @var Response $response */
     try {
         $response = $browser->post($url, $headers, $data);
     } catch (Exception $e) {
         throw new PaytoshiException('Error while posting request', 500, $e);
     }
     $content = json_decode($response->getContent(), true);
     $apiResponse = new ApiResponse($response->isSuccessful(), $response);
     if (!$response->isSuccessful()) {
         if (isset($content['code'])) {
             switch ($content['code']) {
                 case 'NOT_ENOUGH_FUNDS':
                     $apiResponse->setError('Insufficient funds.');
                     break;
                 case 'INVALID_ADDRESS':
                     $apiResponse->setError('Invalid address.');
                     break;
                 case 'FAUCET_DISABLED':
                     $apiResponse->setError('This faucet has been disabled by the owner or the Paytoshi staff.');
                     break;
                 case 'ACCESS_DENIED':
                     $apiResponse->setError('Access denied, please check your apikey.');
                     break;
                 case 'INTERNAL ERROR':
                     $apiResponse->setError('An internal server error has occurred, try again later.');
                     break;
                 case 'BAD_REQUEST':
                     $apiResponse->setError('Invalid request.');
                     break;
                 default:
                     $apiResponse->setError(sprintf("Generic error: %s.", $content['code']));
                     break;
             }
         } else {
             $apiResponse->setError('Generic error.');
         }
         return $apiResponse;
     }
     $apiResponse->setAmount($content['amount']);
     $apiResponse->setRecipient($content['recipient']);
     return $apiResponse;
 }
Esempio n. 20
0
 /**
  * Sends the data to the given registration token, notification key, or topic via the GCM server.
  *
  * @param mixed $data
  * @param String $topic          The value must be a registration token, notification key, or topic. Default global topic.
  * @param array $options         to add along with message, such as collapse_key, time_to_live, delay_while_idle
  *
  * @return bool
  */
 public function sendTo($data, $topic = "/topics/global", array $options = array())
 {
     $headers = array('Authorization: key=' . $this->apiKey, 'Content-Type: application/json');
     $data = array_merge($options, array('data' => $data, 'to' => $topic));
     // Perform the calls (in parallel)
     $this->responses[] = $this->browser->post($this->apiUrl, $headers, json_encode($data));
     $this->browser->getClient()->flush();
     // Determine success
     $message = json_decode($this->responses[0]->getContent(), true);
     if ($message === null || !array_key_exists("message_id", $message) || array_key_exists("failure", $message)) {
         return false;
     }
     return true;
 }
 public function testCachedBrowserClient()
 {
     $currentClient = $this->browser->getClient();
     $arrayCache = new ArrayCache();
     $cachedClient = new CachedClient($currentClient, $arrayCache);
     $this->browser->setClient($cachedClient);
     for ($i = 1; $i <= 3; $i++) {
         $this->translator->translate('This is a test', 'nl');
     }
     $this->assertLessThanOrEqual(2, $cachedClient->getMisses());
     // at most one for the access token, one for the translation
     $this->assertSame(2, $cachedClient->getHits());
     $this->browser->setClient($currentClient);
 }
Esempio n. 22
0
 /**
  * Flush notifications. Triggers the requests.
  *
  * @return array|bool If there are no errors, return true.
  *                    If there were no notifications in the queue, return false.
  *                    Else return an array of information for each notification sent (success, statusCode, headers).
  *
  * @throws \ErrorException
  */
 public function flush()
 {
     if (empty($this->notificationsByServerType)) {
         return false;
     }
     // if GCM is present, we should check for the API key
     if (array_key_exists('GCM', $this->notificationsByServerType)) {
         if (empty($this->apiKeys['GCM'])) {
             throw new \ErrorException('No GCM API Key specified.');
         }
     }
     // for each endpoint server type
     $responses = array();
     foreach ($this->notificationsByServerType as $serverType => $notifications) {
         switch ($serverType) {
             case 'GCM':
                 $responses += $this->sendToGCMEndpoints($notifications);
                 break;
             case 'standard':
                 $responses += $this->sendToStandardEndpoints($notifications);
                 break;
         }
     }
     // if multi curl, flush
     if ($this->browser->getClient() instanceof MultiCurl) {
         /** @var MultiCurl $multiCurl */
         $multiCurl = $this->browser->getClient();
         $multiCurl->flush();
     }
     /** @var Response|null $response */
     $return = array();
     $completeSuccess = true;
     foreach ($responses as $response) {
         if (!isset($response)) {
             $return[] = array('success' => false);
             $completeSuccess = false;
         } elseif (!$response->isSuccessful()) {
             $return[] = array('success' => false, 'statusCode' => $response->getStatusCode(), 'headers' => $response->getHeaders());
             $completeSuccess = false;
         } else {
             $return[] = array('success' => true);
         }
     }
     // reset queue
     $this->notificationsByServerType = null;
     return $completeSuccess ? true : $return;
 }
 /**
  * Does the actual sending
  *
  * @param  \RMS\PushNotificationsBundle\Message\BlackberryMessage $message
  * @return bool
  */
 protected function doSend(BlackberryMessage $message)
 {
     $separator = "mPsbVQo0a68eIL3OAxnm";
     $body = $this->constructMessageBody($message, $separator);
     $browser = new Browser(new Curl());
     $browser->getClient()->setTimeout($this->timeout);
     $listener = new BasicAuthListener($this->appID, $this->password);
     $browser->addListener($listener);
     $url = "https://pushapi.na.blackberry.com/mss/PD_pushRequest";
     if ($this->evaluation) {
         $url = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest";
     }
     $headers = array();
     $headers[] = "Content-Type: multipart/related; boundary={$separator}; type=application/xml";
     $headers[] = "Accept: text/html, *";
     $headers[] = "Connection: Keep-Alive";
     $response = $browser->post($url, $headers, $body);
     return $this->parseResponse($response);
 }
Esempio n. 24
0
 public function send($address, $amount, $ip, $referral = false)
 {
     $apiKey = $this->settingRepository->getApiKey();
     $query = http_build_query(array('apikey' => $apiKey));
     $url = $this->config['api_url'] . '?' . $query;
     $data = http_build_query(array('address' => $address, 'amount' => $amount, 'referral' => $referral, 'ip' => $ip));
     $browser = new Browser();
     $browser->getClient()->setVerifyPeer(false);
     /* @var $response Response */
     try {
         $response = $browser->post($url, array(), $data);
     } catch (Exception $e) {
         throw new PaytoshiException('Failed to send', 500, $e);
     }
     $content = json_decode($response->getContent(), true);
     $apiResponse = new ApiResponse($response->isSuccessful(), $response);
     if (!$response->isSuccessful()) {
         if (isset($content['code'])) {
             switch ($content['code']) {
                 case 'NOT_ENOUGH_FUNDS':
                     $apiResponse->setError('Insufficient funds.');
                     break;
                 case 'INVALID_ADDRESS':
                     $apiResponse->setError('Invalid address.');
                     break;
                 case 'FAUCET_DISABLED':
                     $apiResponse->setError('This faucet has been disabled by the owner or the Paytoshi staff.');
                     break;
                 default:
                     $apiResponse->setError('Failed to send');
                     break;
             }
         } else {
             $apiResponse->setError('Failed to send');
         }
         return $apiResponse;
     }
     $apiResponse->setAmount($content['amount']);
     $apiResponse->setRecipient($content['recipient']);
     return $apiResponse;
 }
 /**
  * {@InheritDoc}
  */
 public function processRequest()
 {
     $this->buzz->getClient()->setTimeout(30);
     try {
         //$startTime = $this->getMicrotimeFloat();
         // Don't verify SSL certificate.
         $this->buzz->getClient()->setVerifyPeer(FALSE);
         $url = $this->getRequestUrl();
         $request = $this->buzz->get($url);
         // @todo check request header, if not 200 throw exception.
         /*$headers = $request->getHeaders();
           if (trim($headers[0]) !== 'HTTP/1.0 200 OK') {
             print 'invalid response'."\n";
             print_r($headers);
             //return;
           }*/
         $requestData = $request->getContent();
         //$endTime = $this->getMicrotimeFloat();
         //$this->requestTime = $endTime - $startTime;
         $this->processRequestData($requestData);
     } catch (ClientException $e) {
         throw new \Exception($e->getMessage());
     }
 }
Esempio n. 26
0
 /**
  * DoRequest
  * @param string $url
  * @param array $params
  * @param string $httpMethod
  * @param array $options
  * @return array
  */
 public function doRequest($url, array $parameters = array(), $httpMethod = 'GET', array $options = array())
 {
     if ($this->options['login']) {
         switch ($this->options['auth_method']) {
             case Client::AUTH_HTTP_PASSWORD:
                 $this->browser->getClient()->setOption(CURLOPT_USERPWD, $this->options['login '] . ':' . $this->options['secret']);
                 break;
             case Client::AUTH_HTTP_TOKEN:
                 $this->browser->getClient()->setOption(CURLOPT_USERPWD, $this->options['login'] . '/token:' . $this->options['secret']);
                 break;
             case Client::AUTH_URL_TOKEN:
             default:
                 $parameters = array_merge(array('login' => $this->options['login'], 'token' => $this->options['secret']), $parameters);
                 break;
         }
     }
     if (!empty($parameters)) {
         $queryString = utf8_encode(http_build_query($parameters, '', '&'));
         if ('GET' === $httpMethod) {
             $url .= '?' . $queryString;
         } else {
             $this->browser->getClient()->setOption(CURLOPT_POST, true);
             $this->browser->getClient()->setOption(CURLOPT_POSTFIELDS, $queryString);
         }
     }
     $this->browser->getClient()->setOption(CURLOPT_URL, $url);
     $this->browser->getClient()->setOption(CURLOPT_PORT, $this->options['http_port']);
     $this->browser->getClient()->setOption(CURLOPT_USERAGENT, $this->options['user_agent']);
     $this->browser->getClient()->setOption(CURLOPT_FOLLOWLOCATION, true);
     $this->browser->getClient()->setOption(CURLOPT_RETURNTRANSFER, true);
     $this->browser->getClient()->setOption(CURLOPT_SSL_VERIFYPEER, false);
     $this->browser->getClient()->setOption(CURLOPT_TIMEOUT, $this->options['timeout']);
     $response = $this->browser->call($url, $httpMethod, $this->headers, json_encode($parameters));
     $this->checkApiLimit($response);
     return array('response' => $response->getContent(), 'headers' => $response->getHeaders(), 'errorNumber' => '', 'errorMessage' => '');
 }
 /**
  * Set Buzz client timeout.
  *
  * @param int $timeout
  */
 public function setTimeout($timeout)
 {
     $this->browser->getClient()->setTimeout($timeout);
 }
 public function __construct()
 {
     $this->browser = new Browser(new Curl());
     $this->browser->getClient()->setVerifyPeer(false);
 }
Esempio n. 29
0
 /**
  * This method is used internally to retrieve a Browser object.
  *
  * <code>
  * $request = $this->getRequest();
  * </code>
  *
  * @return Browser
  *
  * Unittests overwrite this method to retrieve a mock request, so
  * @codeCoverageIgnore
  */
 protected function getRequest()
 {
     $retValue = new Browser(new Curl());
     $retValue->getClient()->setTimeout($this->timeout);
     $retValue->getClient()->setVerifyPeer($this->validateSsl);
     return $retValue;
 }
 /**
  * Dispatch logs to central logging
  */
 public function dispatchLogs()
 {
     if (!$GLOBALS['TL_CONFIG']['central_logging_dispatch_enabled']) {
         return;
     }
     $centralLoggingUrl = $GLOBALS['TL_CONFIG']['central_logging_url'];
     $centralLoggingApiKey = $GLOBALS['TL_CONFIG']['central_logging_api_key'];
     $cacheLogsDisabled = $GLOBALS['TL_CONFIG']['central_logging_cache_logs_disabled'];
     if (empty($centralLoggingUrl) || empty($centralLoggingApiKey)) {
         return;
     }
     $cacheLogMessages = ['Purged the temp folder', 'Purged the internal cache', 'Purged the search cache', 'Purged the script cache', 'Generated the config cache', 'Generated the DCA cache', 'Generated the language cache', 'Generated the DCA extracts'];
     $url = sprintf('%s/api/logs/%s', $centralLoggingUrl, $centralLoggingApiKey);
     $browser = new Browser();
     $browser->getClient()->setTimeout(10);
     $objLogs = $this->database->prepare('
         SELECT *
         FROM tl_log
         WHERE NOT dispatched = 1
             AND NOT do_not_dispatch = 1
         LIMIT 1000
     ')->execute();
     $levelMapping = ['CRON' => 'info', 'CONFIGURATION' => 'info', 'REPOSITORY' => 'info', 'ACCESS' => 'info', 'GENERAL' => 'info', 'ERROR' => 'error'];
     $defaultLevel = 'error';
     $logs = [];
     $sendIds = [];
     while ($objLogs->next() != null) {
         // Remove cache logs from dispatch pile
         if ($cacheLogsDisabled) {
             if (in_array($objLogs->text, $cacheLogMessages)) {
                 $this->database->prepare('
                     UPDATE tl_log
                     SET do_not_dispatch = 1
                     WHERE id = ?
                 ')->execute($objLogs->id);
                 echo sprintf("Remove cache log ID %s from dispatch pile\n", $objLogs->id);
                 continue;
             }
         }
         $level = in_array($objLogs->action, array_keys($levelMapping)) ? $levelMapping[$objLogs->action] : $defaultLevel;
         $message = htmlspecialchars_decode($objLogs->text, ENT_COMPAT);
         $log = ['level' => $level, 'message' => $message, 'created_at' => $objLogs->tstamp, 'context' => ['source' => $objLogs->source, 'function' => $objLogs->func, 'ip' => $objLogs->ip, 'browser' => $objLogs->browser]];
         if ($objLogs->username) {
             $log['context']['username'] = $objLogs->username;
         }
         $logs[] = $log;
         $sendIds[] = $objLogs->id;
     }
     // Send as bulk
     $data = ['logs' => $logs];
     /** @var Response $response */
     $response = $browser->post($url, [], json_encode($data));
     if ($response->getStatusCode() == 200) {
         foreach ($sendIds as $id) {
             $this->database->prepare('
                 UPDATE tl_log
                 SET dispatched = 1
                 WHERE id = ?
             ')->execute($id);
         }
         echo sprintf("Remove log IDs %s from dispatch pile\n", implode(",", $sendIds));
     }
 }