protected function sendPost($url, array $data = array()) { $this->request->setUrl($this->getUrl($url)); $this->request->setMethod(\HttpRequest::METH_POST); if (count($data)) { $this->request->setPostFields($data); } $this->request->send(); }
protected function request($path, $args = array(), $files = array(), $envId = 0, $version = 'v1') { try { $httpRequest = new HttpRequest(); $httpRequest->setMethod(HTTP_METH_POST); $postData = json_encode($args); $stringToSign = "/{$version}{$path}:" . $this->API_ACCESS_KEY . ":{$envId}:{$postData}:" . $this->API_SECRET_KEY; $validToken = Scalr_Util_CryptoTool::hash($stringToSign); $httpRequest->setHeaders(array("X_SCALR_AUTH_KEY" => $this->API_ACCESS_KEY, "X_SCALR_AUTH_TOKEN" => $validToken, "X_SCALR_ENV_ID" => $envId)); $httpRequest->setUrl("http://scalr-trunk.localhost/{$version}{$path}"); $httpRequest->setPostFields(array('rawPostData' => $postData)); foreach ($files as $name => $file) { $httpRequest->addPostFile($name, $file); } $httpRequest->send(); if ($this->debug) { print "<pre>"; var_dump($httpRequest->getRequestMessage()); var_dump($httpRequest->getResponseCode()); var_dump($httpRequest->getResponseData()); } $data = $httpRequest->getResponseData(); return @json_decode($data['body']); } catch (Exception $e) { echo "<pre>"; if ($this->debug) { var_dump($e); } else { var_dump($e->getMessage()); } } }
/** * Makes api request * * @param string $qid The id of the query. * @param array $options optional Query options for the request. * @param string $path optional Uri path for the request (/user by default) * @param string $method optional Http method (GET by default) * @return object Returns object that is an response data. * @throws CloudynException */ public function call($qid, array $options = array(), $path = '/user', $method = 'GET') { $options['qid'] = (string) $qid; $options['out'] = self::OUT_JSON; if (!isset($options['rqid'])) { $options['rqid'] = $this->getRequestId(); } if (!isset($options['apiversion'])) { $options['apiversion'] = '0.4'; } $this->request = $this->createNewRequest(); $this->request->setUrl($this->getUrl() . $path); $this->request->setMethod(constant('HTTP_METH_' . strtoupper($method))); $this->request->setOptions(array('redirect' => 10, 'useragent' => 'Scalr Client (http://scalr.com)')); $this->request->addQueryData($options); //This line is very necessary or HttpResponce will add stored cookies $this->request->resetCookies(); $this->message = $this->tryCall($this->request); $json = $this->message->getBody(); $json = preg_replace('#^[^\\{\\[]+|[^\\}\\]]+$#', '', trim($json)); $obj = json_decode($json); if (isset($obj->status) && $obj->status != 'ok' && isset($obj->message)) { throw new CloudynException('Cloudyn error. ' . $obj->message); } return $obj; }
protected function request($method, $uri, $args) { $parsedUrl = parse_url($this->ec2Url); $uri = "{$parsedUrl['path']}{$uri}"; $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("useragent" => "Scalr (https://scalr.net)")); $args['Version'] = $this->apiVersion; $args['SignatureVersion'] = 2; $args['SignatureMethod'] = "HmacSHA256"; $args['Timestamp'] = $this->getTimestamp(); $args['AWSAccessKeyId'] = $this->accessKeyId; ksort($args); foreach ($args as $k => $v) { $CanonicalizedQueryString .= "&{$k}=" . rawurlencode($v); } $CanonicalizedQueryString = trim($CanonicalizedQueryString, "&"); $url = $parsedUrl['port'] ? "{$parsedUrl['host']}:{$parsedUrl['port']}" : "{$parsedUrl['host']}"; $args['Signature'] = $this->getSignature(array($method, $url, $uri, $CanonicalizedQueryString)); $HttpRequest->setUrl("{$parsedUrl['scheme']}://{$url}{$uri}"); $HttpRequest->setMethod(constant("HTTP_METH_{$method}")); if ($args) { if ($method == 'POST') { $HttpRequest->setPostFields($args); $HttpRequest->setHeaders(array('Content-Type' => 'application/x-www-form-urlencoded')); } else { $HttpRequest->addQueryData($args); } } try { $HttpRequest->send(); $data = $HttpRequest->getResponseData(); if ($HttpRequest->getResponseCode() == 200) { $response = simplexml_load_string($data['body']); if ($this->responseFormat == 'Object') { $json = @json_encode($response); $response = @json_decode($json); } if ($response->Errors) { throw new Exception($response->Errors->Error->Message); } else { return $response; } } else { $response = @simplexml_load_string($data['body']); if ($response) { throw new Exception($response->Error->Message); } throw new Exception(trim($data['body'])); } $this->LastResponseHeaders = $data['headers']; } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception($message); } }
public function OnStartForking() { $db = \Scalr::getDb(); // Get pid of running daemon $pid = @file_get_contents(CACHEPATH . "/" . __CLASS__ . ".Daemon.pid"); $this->Logger->info("Current daemon process PID: {$pid}"); // Check is daemon already running or not if ($pid) { $Shell = new Scalr_System_Shell(); // Set terminal width putenv("COLUMNS=400"); // Execute command $ps = $Shell->queryRaw("ps ax -o pid,ppid,command | grep ' 1' | grep {$pid} | grep -v 'ps x' | grep DBQueueEvent"); $this->Logger->info("Shell->queryRaw(): {$ps}"); if ($ps) { // daemon already running $this->Logger->info("Daemon running. All ok!"); return true; } } $rows = $db->Execute("SELECT history_id FROM webhook_history WHERE status='0'"); while ($row = $rows->FetchRow()) { $history = WebhookHistory::findPk(bin2hex($row['history_id'])); if (!$history) { continue; } $endpoint = WebhookEndpoint::findPk($history->endpointId); $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); if ($endpoint->url == 'SCALR_MAIL_SERVICE') { $request->setUrl('https://my.scalr.com/webhook_mail.php'); } else { $request->setUrl($endpoint->url); } $request->setOptions(array('timeout' => 3, 'connecttimeout' => 3)); $dt = new DateTime('now', new DateTimeZone("UTC")); $timestamp = $dt->format("D, d M Y H:i:s e"); $canonical_string = $history->payload . $timestamp; $signature = hash_hmac('SHA1', $canonical_string, $endpoint->securityKey); $request->addHeaders(array('Date' => $timestamp, 'X-Signature' => $signature, 'X-Scalr-Webhook-Id' => $history->historyId, 'Content-type' => 'application/json')); $request->setBody($history->payload); try { $request->send(); $history->responseCode = $request->getResponseCode(); if ($request->getResponseCode() <= 205) { $history->status = WebhookHistory::STATUS_COMPLETE; } else { $history->status = WebhookHistory::STATUS_FAILED; } } catch (Exception $e) { $history->status = WebhookHistory::STATUS_FAILED; } $history->save(); } }
protected function request($uri, $method, $data) { $httpRequest = new HttpRequest(); $httpRequest->setOptions(array("useragent" => "Scalr (https://scalr.net)")); $httpRequest->setUrl("{$this->apiUrl}{$uri}"); $httpRequest->setMethod($method); $httpRequest->resetCookies(); $httpRequest->addHeaders(array('Cookie' => $this->sessionCookie, 'Content-Type' => 'application/nimbula-v1+json')); switch ($method) { case HTTP_METH_POST: $httpRequest->setRawPostData(json_encode($data)); $httpRequest->addHeaders(array('Content-Type' => 'application/nimbula-v1+json')); break; } try { $httpRequest->send(); $data = $httpRequest->getResponseData(); $result = @json_decode($data['body']); if ($httpRequest->getResponseCode() > 204) { $message = $result->message; if ($message) { if ($message instanceof stdClass) { $r = (array) $message; $msg = ''; foreach ($r as $k => $v) { $msg .= "{$k}: {$v} "; } throw new Exception(trim($msg)); } else { throw new Exception($message); } } throw new Exception($data['body']); } $headers = $httpRequest->getResponseHeader('Set-Cookie'); if ($headers) { if (!is_array($headers)) { if (stristr($headers, "nimbula")) { $this->sessionCookie = $headers; } } else { } } $this->LastResponseHeaders = $data['headers']; return $result; } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception("Nimbula error: {$message}"); } }
private function update($object) { $attr = $object->getAttributes(); $data = $this->encodeResponse($attr); $url = $this->getMethodUrl(array('id' => $object->id)); $req = new HttpRequest(); $req->setUrl($url); $req->setParam('data', $data); $req->setMethod('POST'); $response = $req->perform(); $result = $this->decodeResponse($response); return $this->validateResponse($result); }
function post($url, $post_data) { $hr = new HttpRequest(); $hr->setURL($url); $hr->setMethod('multipart'); foreach ($post_data as $name => $value) { if ($name == 'file') { $hr->addFile(array('name' => 'file', 'path' => $value['path'], 'filename' => $value['filename'])); } else { $hr->addQuery(array('key' => $name, 'value' => $value)); } } $result = $hr->send(); return $result; }
private function Request($method, $uri, $args) { $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)")); $timestamp = $this->GetTimestamp(); $URL = "queue.amazonaws.com"; if ($this->Region != 'us-east-1') { $URL = "{$this->Region}.queue.amazonaws.com"; } //EU URL: eu-west-1.queue.amazonaws.com $args['Version'] = self::API_VERSION; $args['SignatureVersion'] = 2; $args['SignatureMethod'] = "HmacSHA1"; $args['Expires'] = $timestamp; $args['AWSAccessKeyId'] = $this->AWSAccessKeyId; ksort($args); foreach ($args as $k => $v) { $CanonicalizedQueryString .= "&{$k}=" . urlencode($v); } $CanonicalizedQueryString = trim($CanonicalizedQueryString, "&"); $args['Signature'] = $this->GetRESTSignature(array($method, $URL, $uri, $CanonicalizedQueryString)); $HttpRequest->setUrl("https://{$URL}{$uri}"); $HttpRequest->setMethod(constant("HTTP_METH_{$method}")); if ($args) { $HttpRequest->addQueryData($args); } try { $HttpRequest->send(); //$info = $HttpRequest->getResponseInfo(); $data = $HttpRequest->getResponseData(); $this->LastResponseHeaders = $data['headers']; $response = simplexml_load_string($data['body']); if ($response->Error) { throw new Exception($response->Error->Message); } else { return $response; } } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception($message); } }
public function testGeneral() { $httpRequest = new HttpRequest('http://tuoitre.com.vn/conduongcuqua?q=example_query&page=2&t[]=4'); $this->assertEquals(['example_query'], $httpRequest->getList('q')); $this->assertEquals('example_query', $httpRequest->getParam('q')); $this->assertEquals('example_query', $httpRequest->getString('q')); $defaultValue = 'testvalue'; $this->assertEmpty($httpRequest->getGET()); $this->assertEmpty($httpRequest->getPOST()); $this->assertNotEmpty($httpRequest->getQuery()); $this->assertEmpty($httpRequest->getPOST()); $this->assertEquals('2', $httpRequest->getParam('page')); $this->assertEquals(2, $httpRequest->getInt('page')); $this->assertEquals(['4'], $httpRequest->getArray('t')); $this->assertEmpty([], $httpRequest->getArray('no_array')); $this->assertEquals([1], $httpRequest->getArray('no_array', [1])); $this->assertEquals($defaultValue, $httpRequest->getParam('no_query', $defaultValue)); $this->assertEquals($defaultValue, $httpRequest->getString('no_query', $defaultValue)); $this->assertEquals($defaultValue, $httpRequest->getParam('no_query', $defaultValue)); $this->assertTrue($httpRequest->isMethod('get')); $httpRequest->getResponse(); $this->assertEmpty($httpRequest->getFragment()); $httpRequest->setMethod('post'); $this->assertTrue($httpRequest->isPost()); $exception = new \RuntimeException('issue'); $httpRequest->setException($exception); $this->assertEquals($exception, $httpRequest->getException()); $httpRequest->example_params = 12; $this->assertEquals($httpRequest->example_params, 12); $httpRequest->setPath('/'); $this->assertEquals($httpRequest->getPath(), '/'); $httpRequest->setDispatched(false); $this->assertFalse($httpRequest->isDispatched()); $httpRequest->setControllerName('\\Platform\\Core\\Controller\\HomeController'); $httpRequest->setActionName('index'); $this->assertEquals($httpRequest->getControllerName(), '\\Platform\\Core\\Controller\\HomeController'); $this->assertEquals($httpRequest->getActionName(), 'index'); $httpRequest->dispatch(); $httpRequest->setParams(['more' => '2']); $this->assertNotEmpty($httpRequest->getParams()); $this->assertEquals('2', $httpRequest->getParam('more')); $httpRequest->getFullControllerName(); }
public function getValue(DBFarmRole $dbFarmRole, Scalr_Scaling_FarmRoleMetric $farmRoleMetric) { $start_time = microtime(true); $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "Scalr (http://scalr.net) HTTPResponseTime Scaling Sensor", "connecttimeout" => 10)); $HttpRequest->setUrl($farmRoleMetric->getSetting(self::SETTING_URL)); $HttpRequest->setMethod(constant("HTTP_METH_GET")); try { $HttpRequest->send(); } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception("HTTPResponseTime Scaling Sensor cannot get value: {$message}"); } $retval = round(microtime(true) - $start_time, 2); return array($retval); }
private function Request($method, $uri, $request_body, $query_args, $headers = array()) { $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)")); $timestamp = $this->GetTimestamp(); $signature = $this->GetRESTSignature($timestamp); $HttpRequest->setUrl("https://cloudfront.amazonaws.com/" . self::API_VERSION . $uri); $HttpRequest->setMethod($method); if ($query_args) { $HttpRequest->addQueryData($query_args); } if ($request_body) { if ($method == constant("HTTP_METH_POST")) { $HttpRequest->setRawPostData(trim($request_body)); } else { $HttpRequest->setPutData(trim($request_body)); } $headers["Content-type"] = "text/xml"; } $headers["Date"] = $timestamp; $headers["Authorization"] = "AWS {$this->AWSAccessKeyId}:{$signature}"; $HttpRequest->addHeaders($headers); try { $HttpRequest->send(); //$info = $HttpRequest->getResponseInfo(); $data = $HttpRequest->getResponseData(); $this->LastResponseHeaders = $data['headers']; return $data['body']; } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception($message); } }
public function request($method, stdClass $params = null, $namespace = null) { if (!$namespace) { $namespace = $this->namespace; } $requestObj = new stdClass(); $requestObj->id = microtime(true); $requestObj->method = $method; $requestObj->params = new stdClass(); $this->walkSerialize($params, $requestObj->params, 'underScope'); $jsonRequest = $this->cryptoTool->encrypt(json_encode($requestObj), $this->dbServer->GetKey(true)); $dt = new DateTime('now', new DateTimeZone("UTC")); $timestamp = $dt->format("D d M Y H:i:s e"); $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetKey(true), 1)); $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); // If no VPC router communicating via local inteface (Scalr should be setup within the esame network) $requestHost = $this->dbServer->getSzrHost() . ":{$this->port}"; if ($this->isVPC) { $routerFarmRoleId = $this->dbServer->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID); if ($routerFarmRoleId) { $routerRole = DBFarmRole::LoadByID($routerFarmRoleId); } else { $routerRole = $this->dbServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); } if ($routerRole) { // No public IP need to use proxy if (!$this->dbServer->remoteIp) { $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80"; $request->addHeaders(array("X-Receiver-Host" => $this->dbServer->localIp, "X-Receiver-Port" => $this->port)); // There is public IP, can use it } else { $requestHost = "{$this->dbServer->remoteIp}:{$this->port}"; } } } $request->setUrl("http://{$requestHost}/{$namespace}"); $request->setOptions(array('timeout' => $this->timeout, 'connecttimeout' => 10)); $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId)); $request->setBody($jsonRequest); try { // Send request $request->send(); $this->debug['responseCode'] = $request->getResponseCode(); $this->debug['fullResponse'] = $request->getRawResponseMessage(); if ($request->getResponseCode() == 200) { $response = $request->getResponseData(); $body = $this->cryptoTool->decrypt($response['body'], $this->dbServer->GetKey(true)); $jResponse = @json_decode($body); if ($jResponse->error) { throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data}"); } return $jResponse; } else { $response = $request->getResponseData(); throw new Exception(sprintf("Unable to perform request to scalarizr: %s (%s)", $response['body'], $request->getResponseCode())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } if (stristr($msg, "Namespace not found")) { $msg = "Feature not supported by installed version of scalarizr. Please update it to the latest version and try again."; } throw new Exception(sprintf("Unable to perform request to scalarizr: %s", $msg)); } }
public function removeUser($id) { $url = $this->makeServiceURL(self::API_USER_BASE_URL, '/user/' . $id); $req = new HttpRequest(); $req->setUrl($url); $req->setMethod('DELETE'); return $req->perform(); }
<?php $request = new HttpRequest(); $request->setUrl('https://mockbin.com/har'); $request->setMethod(HTTP_METH_GET); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
private function request($method, $params = null) { $requestObj = new stdClass(); $requestObj->id = microtime(true); $requestObj->method = $method; $requestObj->params = $params; $jsonRequest = json_encode($requestObj); $newEncryptionProtocol = false; //TODO: if ($this->dbServer->farmRoleId) { if ($this->dbServer->IsSupported('2.7.7')) { $newEncryptionProtocol = true; } } $dt = new DateTime('now', new DateTimeZone("UTC")); $timestamp = $dt->format("D d M Y H:i:s e"); if ($newEncryptionProtocol) { $jsonRequest = $this->cryptoTool->encrypt($jsonRequest, $this->dbServer->GetKey(true)); $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetKey(true), 1)); } else { $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 1)); } $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); $requestHost = $this->dbServer->getSzrHost() . ":{$this->port}"; if ($this->isVPC) { $routerFarmRoleId = $this->dbServer->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID); if ($routerFarmRoleId) { $routerRole = DBFarmRole::LoadByID($routerFarmRoleId); } else { $routerRole = $this->dbServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); } if ($routerRole) { // No public IP need to use proxy if (!$this->dbServer->remoteIp) { $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80"; $request->addHeaders(array("X-Receiver-Host" => $this->dbServer->localIp, "X-Receiver-Port" => $this->port)); // There is public IP, can use it } else { $requestHost = "{$this->dbServer->remoteIp}:{$this->port}"; } } } $request->setUrl($requestHost); $request->setOptions(array('timeout' => $this->timeout, 'connecttimeout' => $this->timeout)); $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId)); $request->setBody($jsonRequest); try { // Send request $request->send(); if ($request->getResponseCode() == 200) { $response = $request->getResponseData(); $body = $response['body']; if ($newEncryptionProtocol) { $body = $this->cryptoTool->decrypt($body, $this->dbServer->GetKey(true)); } $jResponse = @json_decode($body); if ($jResponse->error) { throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data} ({$response['body']})"); } return $jResponse; } else { throw new Exception(sprintf("Unable to perform request to update client: %s", $request->getResponseCode())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } throw new Exception(sprintf("Unable to perform request to update client: %s", $msg)); } }
/** * Create new object on S3 Bucket * * @param string $object_path * @param string $bucket_name * @param string $filename * @param string $object_content_type * @param string $object_permissions * @return bool */ public function CreateObject($object_path, $bucket_name, $filename, $object_content_type, $object_permissions = "public-read") { if (!file_exists($filename)) { Core::RaiseWarning("{$filename} - no such file."); return false; } $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array( "redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)" ) ); $timestamp = $this->GetTimestamp(true); $data_to_sign = array("PUT", "", $object_content_type, $timestamp, "x-amz-acl:{$object_permissions}","/{$bucket_name}/{$object_path}"); $signature = $this->GetRESTSignature($data_to_sign); $HttpRequest->setUrl("http://{$bucket_name}.s3.amazonaws.com/{$object_path}"); $HttpRequest->setMethod(constant("HTTP_METH_PUT")); $headers["Content-type"] = $object_content_type; $headers["x-amz-acl"] = $object_permissions; $headers["Date"] = $timestamp; $headers["Authorization"] = "AWS {$this->AWSAccessKeyId}:{$signature}"; $HttpRequest->addHeaders($headers); $HttpRequest->setPutFile($filename); try { $HttpRequest->send(); $info = $HttpRequest->getResponseInfo(); if ($info['response_code'] == 200) return true; else { $xml = @simplexml_load_string($HttpRequest->getResponseBody()); return $xml->Message; } } catch (HttpException $e) { Core::RaiseWarning($e->__toString(), E_ERROR); return false; } }
protected function sendRequest($uri, $method, $data = null) { try { $request = new HttpRequest("https://{$this->domain}.chargify.com{$uri}"); $request->setHeaders(array('Content-Type' => 'application/json', 'Authorization' => 'Basic ' . base64_encode("{$this->apiKey}:x"))); $request->setOptions(array('httpauth' => "{$this->apiKey}:x", 'timeout' => 45, 'connecttimeout' => 45, 'ssl' => array('version' => 1))); $request->setMethod(constant("HTTP_METH_{$method}")); if ($method == 'POST' && $data) { $request->setBody($data); } if ($method == 'PUT') { $request->addPutData($data); } } catch (Exception $e) { //TODO: throw $e; } $request->send(); if ($request->getResponseCode() == 500) { throw new Exception("Unable to proceed your request at the moment. Please try again later."); } if ($request->getResponseCode() == 404) { throw new Exception("Unable to proceed your request. Please contact billing@scalr.net to get help."); } return $request; }
/** * * adapt Solarium_Client_Request to HttpRequest * * {@link http://us.php.net/manual/en/http.constants.php * HTTP Predefined Constant} * * @param Solarium_Client_Request $request * @param HttpRequest */ public function toHttpRequest($request) { $url = $this->getBaseUri() . $request->getUri(); $httpRequest = new HttpRequest($url); $headers = array(); foreach ($request->getHeaders() as $headerLine) { list($header, $value) = explode(':', $headerLine); if ($header = trim($header)) { $headers[$header] = trim($value); } } switch ($request->getMethod()) { case Solarium_Client_Request::METHOD_GET: $method = HTTP_METH_GET; break; case Solarium_Client_Request::METHOD_POST: $method = HTTP_METH_POST; $httpRequest->setBody($request->getRawData()); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/xml; charset=utf-8'; } break; case Solarium_Client_Request::METHOD_HEAD: $method = HTTP_METH_HEAD; break; default: throw new Solarium_Exception('Unsupported method: ' . $request->getMethod()); } $httpRequest->setMethod($method); $httpRequest->setOptions(array('timeout' => $this->getTimeout())); $httpRequest->setHeaders($headers); return $httpRequest; }
public function getActualConfig() { if (!$this->_plugin instanceof FeedPlugin) { return false; } $request = new HttpRequest(); $type = "pluginConfig"; $response = $this->getAction($this->getVersion()); $body = json_decode($response->getBody()); if (!isset($body->{$type})) { return $response; } else { $url = $body->{$type}; } $request->setUrl($url); $request->setHeaders($this->getSignHeader()); $request->setHeaders($this->_defaultHeader()); $request->setMethod('GET'); /** @var HttpResponse $response */ $response = $this->_client->doRequest($request); $body = json_decode($response->getBody()); return $body; }
/** * Perform any request * * @param string method request method, e.g. HttpConstants::GET * @param var parameters * @param array headers default array() * @return peer.http.HttpResponse response object * @throws io.IOException */ public function request($method, $parameters, $headers = array()) { $r = new HttpRequest($this->url); $r->setMethod($method); $r->setParameters($parameters); $r->addHeaders($headers); return $this->send($r); }
/** * Send message to instance * @param Scalr_Messaging_Msg $message * @return Scalr_Messaging_Msg */ public function SendMessage(Scalr_Messaging_Msg $message, $isEventNotice = false, $delayed = false) { $startTime = microtime(true); if ($this->farmId && $message->getName() != 'BeforeHostTerminate') { if ($this->GetFarmObject()->Status == FARM_STATUS::TERMINATED) { $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::FAILED, $message->messageId)); return; } } // // To avoid message flood if server cannot respond // Protection from DDOS // Log only right now /* $pendingMessagesCount = $this->Db->GetOne("SELECT COUNT(*) FROM messages WHERE status = '0' OR server_id = ?", array( $this->serverId )); if ($pendingMessagesCount > 50) { if ($message->serverId != $this->serverId) { $this->SetProperty('tmp.flood-alert', 1); } } */ // Ignore OLD messages (ami-scripts) if (!$this->IsSupported("0.5")) { return; } // Put access data and reserialize message $pl = PlatformFactory::NewPlatform($this->platform); $pl->PutAccessData($this, $message); $logger = Logger::getLogger('DBServer'); $serializer = Scalr_Messaging_XmlSerializer::getInstance(); $cryptoTool = \Scalr::getContainer()->srzcrypto($this->GetKey(true)); if ($this->GetProperty(\SERVER_PROPERTIES::SZR_MESSAGE_FORMAT) == 'json') { $serializer = Scalr_Messaging_JsonSerializer::getInstance(); $rawMessage = $serializer->serialize($message); $messageType = 'json'; } else { $rawMessage = $serializer->serialize($message); $messageType = 'xml'; } //$rawJsonMessage = @json_encode($message); $time = microtime(true) - $startTime; if (!$this->Db->GetOne("SELECT COUNT(*) FROM `messages` WHERE `messageid` = ? AND `server_id` = ?", [$message->messageId, $this->serverId])) { // Add message to database $this->Db->Execute("INSERT INTO messages SET\n `messageid` = ?,\n `processing_time` = ?,\n `server_id` = ?,\n `event_server_id` = ?,\n `message` = ?,\n `type` = 'out',\n `message_name` = ?,\n `handle_attempts` = ?,\n `message_version` = ?,\n `dtlasthandleattempt` = NOW(),\n `dtadded` = NOW(),\n `message_format` = ?,\n `event_id` = ?\n ON DUPLICATE KEY UPDATE handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW()\n ", array($message->messageId, $time, $this->serverId, $message->serverId, $rawMessage, $message->getName(), $delayed ? '0' : '1', 2, $messageType, isset($message->eventId) ? $message->eventId : '')); } else { $this->Db->Execute("UPDATE messages SET handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW() WHERE messageid = ? AND server_id = ?", array($message->messageId, $this->serverId)); } if ($delayed) { return $message; } $isVPC = false; if ($this->farmId) { if (DBFarm::LoadByID($this->farmId)->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) { $isVPC = true; } } if (!$this->remoteIp && !$this->localIp && !$isVPC) { return; } $cryptoTool->setCryptoKey($this->GetKey(true)); $encMessage = $cryptoTool->encrypt($rawMessage); $timestamp = date("c", time()); $signature = $cryptoTool->sign($encMessage, null, $timestamp); try { $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); $ctrlPort = $this->getPort(self::PORT_CTRL); $requestHost = $this->getSzrHost() . ":{$ctrlPort}"; if ($isVPC) { $routerFarmRoleId = $this->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID); if ($routerFarmRoleId) { $routerRole = DBFarmRole::LoadByID($routerFarmRoleId); } else { $routerRole = $this->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); } if ($routerRole) { // No public IP need to use proxy if (!$this->remoteIp) { $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80"; $request->addHeaders(array("X-Receiver-Host" => $this->localIp, "X-Receiver-Port" => $ctrlPort)); // There is public IP, can use it } else { $requestHost = "{$this->remoteIp}:{$ctrlPort}"; } } } //Prepare request $request->setUrl("http://{$requestHost}/control"); $request->setOptions(array('timeout' => \Scalr::config('scalr.system.instances_connection_timeout'), 'connecttimeout' => \Scalr::config('scalr.system.instances_connection_timeout'))); $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, 'X-Server-Id' => $this->serverId)); if ($messageType == 'json') { $request->addHeaders(array('Content-type' => 'application/json')); } $request->setBody($encMessage); // Send request $request->send(); // Process response if ($request->getResponseCode() == 201) { $logger->info(sprintf("[FarmID: %s] Sending message '%s' via REST to server '%s' (server_id: %s) completed", $this->farmId, $message->getName(), $this->remoteIp, $this->serverId)); if (in_array($message->getName(), array('ExecScript'))) { $this->Db->Execute("DELETE FROM messages WHERE messageid = ?", array($message->messageId)); } else { if ($messageType != 'json') { $this->Db->Execute("UPDATE messages SET status = ?, message = '' WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId)); } else { $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId)); } if (!empty($message->eventId)) { $this->Db->Execute("UPDATE events SET msg_sent = msg_sent + 1 WHERE event_id = ?", array($message->eventId)); } } } else { $logger->warn(sprintf("[FarmID: %s] Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $this->farmId, $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $request->getResponseStatus())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } if ($this->farmId) { $logger->warn(new FarmLogMessage($this->farmId, sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg), $this->serverId)); } else { $logger->fatal(sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg)); } return false; } return $message; }
/** * @return IHttpRequest */ public function factory() { $useFilter = !in_array(ini_get('filter.default'), ['', 'unsafe_raw']) || ini_get('filter.default_flags'); $post = $useFilter ? filter_input_array(INPUT_POST, FILTER_UNSAFE_RAW) : (empty($_POST) ? [] : $_POST); $cookies = $useFilter ? filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW) : (empty($_COOKIE) ? [] : $_COOKIE); $blacklist = '\\x09\\x0A\\x0D\\x20-\\x7E\\xA0-\\x{10FFFF}'; $chars = '~^[' . $blacklist . ']*+\\z~u'; if (!$this->binary) { $list = [&$post, &$cookies]; while (list($key, $source) = each($list)) { foreach ($source as $k => $v) { if (is_string($k) && (!preg_match($chars, $k) || preg_last_error())) { unset($list[$key][$k]); } else { if (is_array($v)) { $list[$key][$k] = $v; $list[] =& $list[$key][$k]; } else { $list[$key][$k] = (string) preg_replace('~[^' . $blacklist . ']+~u', '', $v); } } } } unset($list, $key, $source, $k, $v); } $uploadList = []; $list = []; if (!empty($_FILES)) { foreach ($_FILES as $k => $v) { if (!$this->binary && is_string($k) && (!preg_match($chars, $k) || preg_last_error())) { continue; } $v['@'] =& $uploadList[$k]; $list[] = $v; } } while (list(, $upload) = each($list)) { if (!isset($upload['name'])) { continue; } else { if (!is_array($upload['name'])) { if (!$this->binary && (!preg_match($chars, $upload['name']) || preg_last_error())) { $upload['name'] = ''; } if ($upload['error'] !== UPLOAD_ERR_NO_FILE) { $upload['@'] = new Upload($upload); } continue; } } foreach ($upload['name'] as $k => $foo) { if (!$this->binary && is_string($k) && (!preg_match($chars, $k) || preg_last_error())) { continue; } $list[] = ['name' => $upload['name'][$k], 'type' => $upload['type'][$k], 'size' => $upload['size'][$k], 'tmp_name' => $upload['tmp_name'][$k], 'error' => $upload['error'][$k], '@' => &$upload['@'][$k]]; } } $remoteAddress = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null; $remoteHost = isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null; $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null; if ($method === 'POST' && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']) && preg_match('#^[A-Z]+\\z#', $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { $method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']; } $headers = []; foreach ($_SERVER as $k => $v) { if (strncmp($k, 'HTTP_', 5) == 0) { $k = substr($k, 5); } else { if (strncmp($k, 'CONTENT_', 8)) { continue; } } $headers[strtr($k, '_', '-')] = $v; } $httpRequest = new HttpRequest(); $httpRequest->setUrl(Url::getCurrent()); $httpRequest->setMethod($method); $httpRequest->setPost($post); $httpRequest->setUploadList($uploadList); $httpRequest->setCookies($cookies); $httpRequest->setHeaders($headers); $httpRequest->setRemoteAddress($remoteAddress); $httpRequest->setRemoteHost($remoteHost); $httpRequest->setBody(file_get_contents('php://input')); return $httpRequest; }
public function request($command, $args = array(), $responseCmd = null) { if (empty($command)) { throw new Scalr_Service_Cloud_Cloudstack_Exception(NO_COMMAND_MSG, NO_COMMAND); } if (!is_array($args)) { throw new Scalr_Service_Cloud_Cloudstack_Exception(sprintf(WRONG_REQUEST_ARGS_MSG, $args), WRONG_REQUEST_ARGS); } foreach ($args as $key => $value) { if ($value == "") { unset($args[$key]); } // Workaround for zones. Doesn't work in uCLoud becuase listZones not supported if ($key == 'zoneid' && $value != '' && $this->platformName != 'ucloud') { if (!$this->zonesCache) { foreach ($this->listZones() as $zone) { $this->zonesCache[$zone->name] = $zone->id; } } if ($this->zonesCache[$value]) { $args[$key] = $this->zonesCache[$value]; } else { throw new Scalr_Service_Cloud_Cloudstack_Exception("Availability zone '{$value}' no longer supported"); } } } // Building the query $args['apikey'] = $this->apiKey; $args['command'] = $command; $args['response'] = "json"; ksort($args); $query = http_build_query($args); $query = str_replace("+", "%20", $query); $query .= "&signature=" . $this->getSignature(strtolower($query)); // var_dump($query); $httpRequest = new HttpRequest(); $httpRequest->setMethod(HTTP_METH_GET); $url = $this->endpoint . "?" . $query; $httpRequest->setOptions(array("redirect" => 2, "useragent" => "Scalr", 'timeout' => 10, 'connecttimeout' => 10)); $httpRequest->setUrl($url); $httpRequest->send(); $code = $httpRequest->getResponseCode(); $data = $httpRequest->getResponseData(); if (empty($data)) { throw new Scalr_Service_Cloud_Cloudstack_Exception(NO_DATA_RECEIVED_MSG, NO_DATA_RECEIVED); } //echo $data['body'] . "\n"; $result = @json_decode($data['body']); if (empty($result)) { throw new Scalr_Service_Cloud_Cloudstack_Exception("The server did not issue a json response ({$code}): {$data['body']}", NO_VALID_JSON_RECEIVED); } if (!$responseCmd) { $responseCmd = strtolower($command); } $propertyResponse = "{$responseCmd}response"; if (!property_exists($result, $propertyResponse)) { if (property_exists($result, "errorresponse") && property_exists($result->errorresponse, "errortext")) { throw new Scalr_Service_Cloud_Cloudstack_Exception($result->errorresponse->errortext); } else { throw new Scalr_Service_Cloud_Cloudstack_Exception(sprintf("Unable to parse the response ({$command}). Got code %d and message: %s", $code, $data['body'])); } } $response = $result->{$propertyResponse}; if ($code > 400) { /* * Request to cloudstack failed. general error (503) ( * apikey=very-secret-key& * command=deployVirtualMachine& * group=base-ubuntu1004-devel& * response=json& * serviceofferingid=85& * templateid=1670& * userdata=ZmFybWlkPTc2NDQ7cm9sZT1iYXNlLGNoZWY7ZXZlbnRoYW5kbGVydXJsPW15LnNjYWxyLm5ldDtoYXNoPTRjNGNmY2MxZWQ1NjlhO3JlYWxyb2xlbmFtZT1iYXNlLXVidW50dTEwMDQtZGV2ZWw7aHR0cHByb3RvPWh0dHBzO3JlZ2lvbj0yO3N6cl9rZXk9cDM2b2pXRGt0KytvK1RjSm1adXY0cmJMQWV3RUlPQ1hVM1lVWEtoMUFGdGtER1ZWYzVDV0lRPT07c2VydmVyaWQ9ZDM2YTBjOWUtZDJhMS00NTg0LTlkNjctN2E4YmE1NDMwMTM5O3AycF9wcm9kdWNlcl9lbmRwb2ludD1odHRwczovL215LnNjYWxyLm5ldC9tZXNzYWdpbmc7cXVlcnllbnZfdXJsPWh0dHBzOi8vbXkuc2NhbHIubmV0L3F1ZXJ5LWVudjtiZWhhdmlvcnM9YmFzZSxjaGVmO2Zhcm1fcm9sZWlkPTM2NzIzO3JvbGVpZD0zNjM3MTtlbnZfaWQ9MzQxNDtvd25lcl9lbWFpbD0%3D& * zoneid=2& * signature=PV02IqoAjmPlkAwd9TYCuAG4kp4%3D * ) */ throw new Exception("Request to cloudstack failed. {$response->errortext} ({$response->errorcode}) ({$query})"); } // list handling : most of lists are on the same pattern as listVirtualMachines : // { "listvirtualmachinesresponse" : { "virtualmachine" : [ ... ] } } preg_match('/list(\\w+)s/', strtolower($command), $listMatches); if (!empty($listMatches)) { $objectName = $listMatches[1]; if (property_exists($response, $objectName)) { $resultArray = $response->{$objectName}; if (is_array($resultArray)) { return $resultArray; } } else { // sometimes, the 's' is kept, as in : // { "listasyncjobsresponse" : { "asyncjobs" : [ ... ] } } $objectName = $listMatches[1] . "s"; if (property_exists($response, $objectName)) { $resultArray = $response->{$objectName}; if (is_array($resultArray)) { return $resultArray; } } } } return $response; }
/** * The CreateBucket operation creates a bucket. Not every string is an acceptable bucket name. * * @param string $bucket_name * @return string */ public function CreateBucket($bucket_name, $region = 'us-east-1') { $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)")); $timestamp = $this->GetTimestamp(true); switch ($region) { case "us-east-1": $request = ""; break; case "us-west-1": $request = "<CreateBucketConfiguration><LocationConstraint>us-west-1</LocationConstraint></CreateBucketConfiguration>"; break; case "eu-west-1": $request = "<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>"; break; } $data_to_sign = array("PUT", "", "", $timestamp, "/{$bucket_name}/"); $signature = $this->GetRESTSignature($data_to_sign); $HttpRequest->setUrl("https://{$bucket_name}.s3.amazonaws.com/"); $HttpRequest->setMethod(constant("HTTP_METH_PUT")); $headers = array("Content-length" => strlen($request), "Date" => $timestamp, "Authorization" => "AWS {$this->AWSAccessKeyId}:{$signature}"); $HttpRequest->addHeaders($headers); if ($request != '') { $HttpRequest->setPutData($request); } try { $HttpRequest->send(); $info = $HttpRequest->getResponseInfo(); if ($info['response_code'] == 200) { return true; } else { if ($HttpRequest->getResponseBody()) { $xml = @simplexml_load_string($HttpRequest->getResponseBody()); throw new Exception((string) $xml->Message); } else { throw new Exception(_("Cannot create S3 bucket at this time. Please try again later.")); } } } catch (HttpException $e) { throw new Exception($e->__toString()); } }
public function oneByteBody() { $r = new HttpRequest(new URL('http://example.com/')); $r->setMethod(HttpConstants::POST); $r->setParameters(new RequestData('1')); $this->assertEquals("POST / HTTP/1.1\r\nConnection: close\r\nHost: example.com\r\nContent-Length: 1\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n", $r->getHeaderString()); }
/** * * adapt Request to HttpRequest * * {@link http://us.php.net/manual/en/http.constants.php * HTTP Predefined Constant} * * {@link http://us.php.net/manual/en/http.request.options.php * HttpRequest options} * * @throws InvalidArgumentException * @param Request $request * @param Endpoint $endpoint * @param HttpRequest * @return \HttpRequest */ public function toHttpRequest($request, $endpoint) { $url = $endpoint->getBaseUri() . $request->getUri(); $httpRequest = new \HttpRequest($url); $headers = array(); foreach ($request->getHeaders() as $headerLine) { list($header, $value) = explode(':', $headerLine); if ($header = trim($header)) { $headers[$header] = trim($value); } } // Try endpoint authentication first, fallback to request for backwards compatibility $authData = $endpoint->getAuthentication(); if (empty($authData['username'])) { $authData = $request->getAuthentication(); } if (!empty($authData['username']) && !empty($authData['password'])) { $headers['Authorization'] = 'Basic ' . base64_encode($authData['username'] . ':' . $authData['password']); } switch ($request->getMethod()) { case Request::METHOD_GET: $method = HTTP_METH_GET; break; case Request::METHOD_POST: $method = HTTP_METH_POST; if ($request->getFileUpload()) { $httpRequest->addPostFile('content', $request->getFileUpload(), 'application/octet-stream; charset=binary'); } else { $httpRequest->setBody($request->getRawData()); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/xml; charset=utf-8'; } } break; case Request::METHOD_HEAD: $method = HTTP_METH_HEAD; break; default: throw new InvalidArgumentException('Unsupported method: ' . $request->getMethod()); } $httpRequest->setMethod($method); $httpRequest->setOptions(array('timeout' => $endpoint->getTimeout(), 'connecttimeout' => $endpoint->getTimeout(), 'dns_cache_timeout' => $endpoint->getTimeout())); $httpRequest->setHeaders($headers); return $httpRequest; }
public function head($url) { if (!is_array($url)) { $req = new HttpRequest($url); $req->setMethod('HEAD'); return $this->process($req); } $reqs = array(); foreach ($url as $key => $_url) { $req = new HttpRequest($_url); $req->setMethod('HEAD'); $reqs[$key] = $req; } return $this->process($reqs); }
<?php $request = new HttpRequest(); $request->setUrl('http://mockbin.com/har'); $request->setMethod(HTTP_METH_POST); $request->setCookies(array('bar' => 'baz', 'foo' => 'bar')); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
public function head($url) { $request = new HttpRequest(); $request->setMethod('HEAD'); $request->setUrl($url); $this->doRequest($request); }