/** * 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('User-Agent' => 'solvemedia/PHP', 'Content-Type' => 'application/x-www-form-urlencoded', 'Connection' => 'close'); $content = array('privatekey' => $this->privateKey, 'remoteip' => $remoteIp, 'challenge' => $challenge, 'response' => $response); $browser = new Browser(); try { /** @var Response $resp */ $resp = $browser->post(self::ADCOPY_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()); } /** * 0: true|false * 1: errorMessage (optional) * 2: hash */ $answers = explode("\n", $resp->getContent()); $success = filter_var($answers[0], FILTER_VALIDATE_BOOLEAN); if (!$success) { return new CaptchaResponse($success, $answers[1]); } $hashMaterial = $answers[0] . $challenge . $this->hashKey; $hash = sha1($hashMaterial); if ($hash != $answers[2]) { throw new CaptchaException('Hash verification error'); } return new CaptchaResponse($success); }
/** * Executes a http request. * * @param Request $request The http request. * * @return Response The http response. */ public function execute(Request $request) { $method = $request->getMethod(); $endpoint = $request->getEndpoint(); $params = $request->getParams(); $headers = $request->getHeaders(); try { if ($method === 'GET') { $buzzResponse = $this->client->call($endpoint . '?' . http_build_query($params), $method, $headers, array()); } else { $buzzRequest = new FormRequest(); $buzzRequest->fromUrl($endpoint); $buzzRequest->setMethod($method); $buzzRequest->setHeaders($headers); foreach ($params as $key => $value) { if ($value instanceof Image) { $value = new FormUpload($value->getData()); } $buzzRequest->setField($key, $value); } $buzzResponse = new BuzzResponse(); $this->client->send($buzzRequest, $buzzResponse); } } catch (RequestException $e) { throw new Exception($e->getMessage()); } return static::convertResponse($request, $buzzResponse); }
/** * Sends the message via the GCM server. * * @param mixed $data * @param array $registrationIds * @param array $options * @param string $payload_type * * @return bool */ public function send($data, array $registrationIds = array(), array $options = array(), $payload_type = 'data') { $this->responses = array(); if (!in_array($payload_type, ['data', 'notification'])) { $payload_type = 'data'; } $data = array_merge($options, array($payload_type => $data)); if (isset($options['to'])) { $this->responses[] = $this->browser->post($this->apiUrl, $this->getHeaders(), json_encode($data)); } elseif (count($registrationIds) > 0) { // Chunk number of registration ID's according to the maximum allowed by GCM $chunks = array_chunk($registrationIds, $this->registrationIdMaxCount); // Perform the calls (in parallel) foreach ($chunks as $registrationIds) { $data['registration_ids'] = $registrationIds; $this->responses[] = $this->browser->post($this->apiUrl, $this->getHeaders(), json_encode($data)); } } $this->client->flush(); foreach ($this->responses as $response) { $message = json_decode($response->getContent()); if ($message === null || $message->success == 0 || $message->failure > 0) { return false; } } return true; }
/** * {@inheritdoc} */ public function getLatestResponseHeaders() { if (null === ($response = $this->browser->getLastResponse())) { return; } return ['reset' => (int) $response->getHeader('RateLimit-Reset'), 'remaining' => (int) $response->getHeader('RateLimit-Remaining'), 'limit' => (int) $response->getHeader('RateLimit-Limit')]; }
/** * @param string $token * * @return ProviderMetadata */ public function getUserDetails($token) { try { // Fetch user data list($identifier, $secret) = explode('@', $token); $tokenObject = new TokenCredentials(); $tokenObject->setIdentifier($identifier); $tokenObject->setSecret($secret); $url = 'https://api.bitbucket.org/2.0/user'; $headers = $this->oauthProvider->getHeaders($tokenObject, 'GET', $url); $response = $this->httpClient->get($url, $headers); $data = json_decode($response->getContent(), true); if (empty($data) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('Json error'); } // Fetch email $url = sprintf('https://api.bitbucket.org/1.0/users/%s/emails', $data['username']); $headers = $this->oauthProvider->getHeaders($tokenObject, 'GET', $url); $response = $this->httpClient->get($url, $headers); $emails = json_decode($response->getContent(), true); if (empty($emails) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('Json error'); } $emails = array_filter($emails, function ($emailData) { return true === $emailData['primary']; }); $data['email'] = empty($emails) ? '' : current($emails)['email']; return new ProviderMetadata(['uid' => $data['uuid'], 'nickName' => $data['username'], 'realName' => $data['display_name'], 'email' => $data['email'], 'profilePicture' => $data['links']['avatar']['href'], 'homepage' => $data['links']['html']['href'], 'location' => $data['location']]); } catch (\Exception $e) { throw new \RuntimeException('cannot fetch account details', 0, $e); } }
/** * @Route("/produit/{id}", name="product_plug") * @Template() */ public function plugAction($id) { $browser = new Browser(); $response = $browser->get($this->container->getParameter("back_site") . 'api/products/' . $id); $product = $this->get('jms_serializer')->deserialize($response->getContent(), 'Kali\\Front\\CommandBundle\\Entity\\Product', 'json'); return array('product' => $product, 'site' => $this->container->getParameter("back_site"), 'caracteristics' => $product->getCaracteristics()); }
/** * 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); }
/** * @param string $endpoint * @param string $content * @param array $headers * @param array $files * @return Response */ public function send($endpoint, $content, array $headers = array(), array $files = array()) { // Make headers buzz friendly array_walk($headers, function (&$value, $key) { $value = sprintf('%s: %s', $key, $value); }); if ($files) { // HTTP query content parse_str($content, $fields); // Add files to request foreach ($files as $key => $items) { $fields[$key] = array(); foreach ($items as $name => $item) { $item = new FormUpload($item); if (!is_numeric($name)) { $item->setName($name); } $fields[$key] = $item; } } $response = $this->browser->submit($endpoint, $fields, RequestInterface::METHOD_POST, array_values($headers)); } else { // JSON content $response = $this->browser->post($endpoint, array_values($headers), $content); } return new Response($response->getStatusCode(), $response->getContent()); }
public function sendHeartbeat() { $ip = null; $localIps = $this->getLocalIp(); if (isset($localIps['eth0'])) { $ip = $localIps['eth0']; } elseif (isset($localIps['wlan0'])) { $ip = $localIps['wlan0']; } if (null == $ip) { throw new \Exception('No local IP available.'); } $settings = $this->em->getRepository('AppBundle:Settings')->findAll(); if (count($settings) > 0) { $settings = $settings[0]; } else { throw new \Exception('No settings provided.'); } $buzz = new Browser(); $response = $buzz->post($settings->getHeartbeatUrl(), array('Content-Type' => 'application/json'), json_encode(array('locale_ip' => $ip, 'printbox' => $settings->getPrintboxPid()))); if ($response->isSuccessful()) { return $ip; } throw new \Exception('Heartbeat failed: ' . $settings->getHeartbeatUrl() . ' ' . $response->getStatusCode() . ' ' . $response->getContent()); }
/** * 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; }
/** * 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); }
/** * @dataProvider fileProvider */ public function testYuml(BuilderInterface $builder, $fixture, $config) { $result = $builder->configure($config)->setPath($fixture)->build(); $this->assertInternalType('array', $result); $this->assertGreaterThan(0, count($result)); $b = new Browser(); foreach ($result as $message) { $url = explode(' ', $message); $response = $b->get($url[1]); $contentType = null; switch ($url[0]) { case '<info>PNG</info>': $contentType = 'image/png'; break; case '<info>PDF</info>': $contentType = 'application/pdf'; break; case '<info>URL</info>': $contentType = 'text/html; charset=utf-8'; break; case '<info>JSON</info>': $contentType = 'application/json'; break; case '<info>SVG</info>': $contentType = 'image/svg+xml'; break; } $this->assertEquals($contentType, $response->getHeader('Content-Type')); } }
/** * Submit a request to the API. * * @param Requestable $request * @return object */ public function submit(RequestableInterface $request) { $this->applyDefaultOptions($request); $url = $this->options['host'] . $request->getPath(); $data = Packer::pack($request); return new Response($this->browser->submit($url, $data)); }
/** * @param string $token * * @return ProviderMetadata */ public function getUserDetails($token) { try { // Fetch user data $response = $this->httpClient->get('https://api.github.com/user', ['Authorization' => sprintf('token %s', $token), 'User-Agent' => 'Pickleweb']); $data = json_decode($response->getContent(), true); if (empty($data) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('Json error'); } // Fetch emails if needed if (empty($data['email'])) { $response = $this->httpClient->get('https://api.github.com/user/emails', ['Authorization' => sprintf('token %s', $token), 'User-Agent' => 'Pickleweb']); $emails = json_decode($response->getContent(), true); if (empty($emails) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('Json error'); } $emails = array_filter($emails, function ($emailData) { return true === $emailData['primary']; }); if (!empty($emails)) { $data['email'] = current($emails)['email']; } } return new ProviderMetadata(['uid' => $data['id'], 'nickName' => $data['login'], 'realName' => $data['name'], 'email' => $data['email'], 'profilePicture' => $data['avatar_url'], 'homepage' => $data['html_url'], 'location' => $data['location']]); } catch (\Exception $e) { throw new \RuntimeException('cannot fetch account details', 0, $e); } }
/** * @param Request $request * @return Response */ public function request(Request $request) { $buzzRequest = $this->prepareRequest($request); /** @var BuzzResponse $buzzResponse */ $buzzResponse = $this->browser->send($buzzRequest); return new Response((string) $buzzResponse->getProtocolVersion(), $buzzResponse->getStatusCode(), $buzzResponse->getReasonPhrase(), HeaderConverter::convertRawToAssociative($buzzResponse->getHeaders()), $buzzResponse->getContent()); }
/** * @Route("/category/list", name="category_list") * @Template() */ public function listAction() { $browser = new Browser(); $response = $browser->get($this->container->getParameter("back_site") . 'api/all/category'); $categories = $this->get('jms_serializer')->deserialize($response->getContent(), 'Doctrine\\Common\\Collections\\ArrayCollection', 'json'); return array("categories" => $categories); }
/** * * @param string $path Path (will be appended to the Base URL) * @param array $params * @param mixed $method * @return \SimpleXMLElement */ protected function request($path, array $params = null, $method = RequestInterface::METHOD_GET) { // Full URL $fullUrl = new Url($this->baseUrl . $path); // Additional headers $headers = array('User-Agent: ' . $this->getUserAgentString()); // Got data? if ($method === RequestInterface::METHOD_GET) { if ($params != null && count($params) > 0) { $fullUrl = new Url($this->baseUrl . $path . '?' . http_build_query($params)); } $response = $this->browser->get($fullUrl, $headers); } else { $response = $this->browser->call($fullUrl, $method, $headers, $params); } // Convert XML $xml = @simplexml_load_string($response->getContent()); // Succesful? if ($xml === false) { throw new MollieException('Server did not respond with valid XML.'); } // Error? if ($xml->item != null && (string) $xml->item['type'] == 'error') { throw new MollieException((string) $xml->item->message, intval($xml->item->errorcode)); } return $xml; }
/** * @Route("/slogan", name="site_slogan") * @Template() */ public function sloganAction() { $browser = new Browser(); $response = $browser->get($this->container->getParameter("back_site") . 'api/parameters'); $paramater = $this->get('jms_serializer')->deserialize($response->getContent(), 'Kali\\Front\\SiteBundle\\Entity\\Parameter', 'json'); return array('slogan' => $paramater->getSlogan(), 'site' => $this->container->getParameter("back_site")); }
function it_parses_properly(MessageInterface $messageInterface) { $messageInterface->getContent()->willReturn(<<<JSON [{ \t"command": "settings", \t"settings": { \t\t"basePath": "\\/", \t\t"pathPrefix": "ca\\/", \t\t"ajaxPageState": { \t\t\t"theme": "bicing", \t\t\t"theme_token": "NngnJfQN6FaHhoz6tHcHih5kFdxcm0b7EeWdAgd492M" \t\t} \t}, \t"merge": true }, { \t"command": "insert", \t"method": null, \t"selector": null, \t"data": "[{\\u0022StationID\\u0022:\\u00221\\u0022,\\u0022StationName\\u0022:\\u002201 - C\\\\/ GRAN VIA CORTS CATALANES 760\\u0022,\\u0022DisctrictCode\\u0022:\\u00222\\u0022,\\u0022AddressGmapsLongitude\\u0022:\\u00222.180042000000000000\\u0022,\\u0022AddressGmapsLatitude\\u0022:\\u002241.39795200000000000\\u0022,\\u0022StationAvailableBikes\\u0022:\\u002217\\u0022,\\u0022StationFreeSlot\\u0022:\\u00222\\u0022,\\u0022AddressZipCode\\u0022:\\u002208013\\u0022,\\u0022AddressStreet1\\u0022:\\u0022Gran Via Corts Catalanes\\u0022,\\u0022AddressNumber\\u0022:\\u0022760\\u0022,\\u0022NearbyStationList\\u0022:\\u002224,369,387,426\\u0022,\\u0022StationStatusCode\\u0022:\\u0022OPN\\u0022}]", \t"settings": null }, { \t"command": "insert", \t"method": "prepend", \t"selector": null, \t"data": "", \t"settings": null }] JSON ); $this->browser->post(BicingApi::BICING_URL)->willReturn($messageInterface); $this->getSnapshot()->shouldHaveCount(1); }
/** * Send request and generate response. * * @param Bool secure * * @throws UniversalAnalytics\Exception\InvalidRequestException * * @return Response */ public function send($secure = true) { $buzzBrowser = new Browser(); $buzzBrowser->setClient(new Curl()); $base = $secure ? $this->base_ssl : $this->base; $buzzResponse = $buzzBrowser->submit($base, $this->attributes, RequestInterface::METHOD_POST, array()); return new Response($buzzResponse); }
public function perform($url) { $curl = new Curl(); $curl->setTimeout(30); $curl->setProxy($this->proxy); $browser = new Browser($curl); return $this->serializer->decode($browser->post($url)->getContent(), 'xml'); }
public function it_can_search_with__query(Browser $client, Response $response) { $response->getContent()->shouldBeCalled(); $client->get(sprintf('%s/search?%s', 'http://endpoint', http_build_query(['q' => 'pilkington avenue, birmingham', 'format' => 'json'])), ['User-Agent' => 'Nomatim PHP Library (https://github.com/nixilla/nominatim-consumer); email: not set'])->shouldBeCalled()->willReturn($response); $query = new Query(); $query->setQuery('pilkington avenue, birmingham'); $this->search($query)->shouldReturnAnInstanceOf('Nominatim\\Result\\Collection'); }
/** * @param string $token * * @return ProviderMetadata */ public function getUserDetails($token) { $data = json_decode($this->httpClient->get('https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' . $token)->getContent(), true); if (empty($data) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('cannot fetch account details'); } return new ProviderMetadata(['uid' => $data['id'], 'nickName' => $data['given_name'], 'realName' => $data['name'], 'email' => $data['email'], 'profilePicture' => $data['picture'], 'homepage' => $data['link']]); }
protected function createBrowser($user = null, $password = null) { $browser = new Buzz\Browser(); if ($user) { $browser->addListener(new Buzz\Listener\BasicAuthListener($user, $password)); } return $browser; }
public function testMarkupInValid() { $content = '{"messages":[{"type":"info","message":"The Content-Type was “text/html”. Using the HTML parser."},{"type":"info","message":"Using the schema for HTML with SVG 1.1, MathML 3.0, RDFa 1.1, and ITS 2.0 support."},{"type":"error","lastLine":1,"lastColumn":42,"firstColumn":35,"message":"Element “title” must not be empty.","extract":"ad><title></title></head","hiliteStart":10,"hiliteLength":8}]}'; $response = $this->getMock('Buzz\\Message\\MessageInterface'); $response->expects($this->once())->method("getContent")->will($this->returnValue($content)); $this->browser->expects($this->once())->method("post")->will($this->returnValue($response)); $this->assertFalse($this->validator->isMarkupValid("<!DOCTYPE html><html><head><title></title></head><body></body></html>")); }
/** * 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; }
/** * @param string $key The key * @param string $pass The pass * @return boolean * @throws BadResponseException */ public function authenticate($key, $pass) { $response = $this->browser->get(sprintf('%s/check/password.json?%s', $this->baseUrl, http_build_query(array('key' => $key, 'pass' => $pass)))); if (500 == $response->getStatusCode()) { throw new BadResponseException($response); } return 'true' == $response->getContent() ? true : false; }
protected function getCrawler() { if (null === $this->crawler) { $client = new Browser(); $this->crawler = new Crawler($client->get($this->url)->getContent()); } return $this->crawler; }
/** * Configures the adapter for authentication against the RoboWhois API. */ protected function getDefaultAdapter() { $adapter = new Browser(); $client = new \Buzz\Client\Curl(); $client->setTimeout(5); $adapter->setClient($client); return $adapter; }
public function it_returns_the_correct_historical_object_for_day_data(Browser $browser) { $browser->get($this->baseUrl . '/V?d=3&f=j')->willReturn($this->createResponse($this->dayResponse)); $data = $this->getDataForDay(3); $data->shouldHaveType('Wjzijderveld\\Youless\\Api\\Response\\History'); $data->getValuesInWatt()->shouldBeLike(array(90, 90, 70, 80, 100, 70, 90, 160, 270, 70, 90, 120, 120, 100, 80, 180, 140, 190, 110, 150, 160, 170, 160, 150)); $data->getMeasuredFrom()->shouldBeLike(new DateTime('2014-09-26T00:00:00')); $data->getDeltaInSeconds()->shouldEqual(3600); }