Esempio n. 1
0
 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();
 }
 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();
     }
 }
Esempio n. 3
0
 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());
         }
     }
 }
 public function keyword_search($keyword)
 {
     // 從 Google 取得搜尋結果(HTML原始碼)
     $keyword = urlencode($keyword);
     $url = "https://www.google.com.tw/webhp?hl=zh-TW#hl=zh-TW&q={$keyword}&num=10";
     $httpReq = new HttpRequest();
     $httpReq->setUrl($url);
     $content = $httpReq->submit();
     unset($httpReq);
     $results = array();
     // 分析原始碼並取得每個項目
     if (preg_match_all('/<!--m-->(.*?)<!--n-->/s', $content, $items)) {
         $idx = 0;
         foreach ($items[1] as $key => $item) {
             $resultItem = new ResultItem();
             $resultItem->sequence = $idx + 1;
             $resultItem->title = preg_match('/<a .*?>(.*?)<\\/a>/s', $item, $res) ? trim($res[1]) : "";
             $resultItem->link = urldecode(preg_match('/<h3 class="r"><a href="(.*?)".*?>.*?<\\/a>/s', $item, $res) ? trim($res[1]) : "");
             $resultItem->description = preg_match('/<span class="st">(<span class="f">(.*?)<\\/span>)?(.*?)<\\/span>/s', $item, $res) ? trim($res[3]) : "";
             $resultItem->save_date = str_replace(" - ", "", $res[2]);
             if (trim($resultItem->link) == "") {
                 continue;
             }
             $idx++;
             $results[] = $resultItem;
         }
     }
     return $results;
 }
Esempio n. 5
0
 /**
  * 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;
 }
Esempio n. 6
0
 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);
     }
 }
Esempio n. 7
0
 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}");
     }
 }
Esempio n. 8
0
 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);
 }
Esempio n. 9
0
 public function findWithOptions($options)
 {
     $req = new HttpRequest();
     $url = $this->getMethodUrl($options);
     $req->setUrl($url);
     $req->setParams($options);
     $response = $req->perform();
     $result = $this->decodeResponse($response);
     if (isset($result['error'])) {
         throw new RemoteException($result['error']);
     }
     return $this->createResultDataSet($result);
 }
Esempio n. 10
0
 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);
     }
 }
Esempio n. 11
0
 /**
  * @inheritdoc
  */
 public function format(HttpRequest $request)
 {
     $data = (array) $request->getData();
     $content = http_build_query($data, '', '&', $this->encodingType);
     if (strcasecmp('get', $request->getMethod()) === 0) {
         if (!empty($content)) {
             $url = $request->getUrl();
             $url .= strpos($url, '?') === false ? '?' : '&';
             $url .= $content;
             $request->setUrl($url);
         }
         return $request;
     }
     $request->addHeader('Content-Type', 'application/x-www-form-urlencoded');
     $request->setContent($content);
     return $request;
 }
Esempio n. 12
0
 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);
 }
Esempio n. 13
0
 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);
     }
 }
Esempio n. 14
0
 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();
 }
Esempio n. 16
0
<?php

$request = new HttpRequest();
$request->setUrl('http://exenzo-nl.saas/api/v1/organisation/0nz5d3LV');
$request->setMethod(HTTP_METH_GET);
$request->setHeaders(array('cache-control' => 'no-cache', 'content-type' => 'application/json', 'x-authorization' => 'ORGANISATION_API_TOKEN'));
try {
    $response = $request->send();
    echo $response->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
Esempio n. 17
0
 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));
     }
 }
Esempio n. 18
0
 private function request($path, $method, $data = "")
 {
     $data = trim($data);
     $httpRequest = new HttpRequest();
     $httpRequest->setOptions(array("useragent" => "Scalr (http://scalr.com)"));
     $fullUrl = "{$this->chefServerUrl}{$path}";
     $chunks = parse_url($fullUrl);
     if ($method == 'POST' && $data) {
         if (is_array($data)) {
             $httpRequest->setPostFields($data);
         } else {
             $httpRequest->setBody($data);
         }
     }
     if ($method == 'PUT' && $data) {
         $httpRequest->setPutData($data);
     }
     $httpRequest->setUrl($fullUrl);
     $httpRequest->setMethod(constant("HTTP_METH_{$method}"));
     $tz = @date_default_timezone_get();
     date_default_timezone_set("UTC");
     $timestamp = date("Y-m-d\\TH:i:s\\Z");
     date_default_timezone_set($tz);
     $chunks['path'] = str_replace('//', '/', $chunks['path']);
     $hashedPath = base64_encode(sha1($chunks['path'], true));
     $hashedBody = base64_encode(sha1($data, true));
     $userId = $this->username;
     $str = "Method:{$method}\n" . "Hashed Path:{$hashedPath}\n" . "X-Ops-Content-Hash:{$hashedBody}\n" . "X-Ops-Timestamp:{$timestamp}\n" . "X-Ops-UserId:{$userId}";
     $headers = array('x-ops-sign' => "algorithm=sha1;version=1.0", 'x-chef-version' => "0.10.8", 'x-ops-userid' => $userId, 'x-ops-timestamp' => $timestamp, 'x-ops-content-hash' => $hashedBody, 'content-type' => 'application/json', 'accept' => 'application/json');
     $r = array_merge($headers, $this->sign($str));
     $httpRequest->addHeaders($r);
     $httpRequest->send();
     if ($httpRequest->getResponseCode() == 401) {
         throw new Exception("Failed to authenticate as {$userId}. Ensure that your node_name and client key are correct.");
     }
     if ($httpRequest->getResponseCode() == 404) {
         throw new Exception("Client not found or parameters are not valid");
     } else {
         if ($httpRequest->getResponseCode() <= 205) {
             $data = $httpRequest->getResponseData();
             $retval = $data['body'] ? json_decode($data['body']) : true;
         } else {
             if ($httpRequest->getResponseCode() > 400) {
                 $data = $httpRequest->getResponseData();
                 $msg = $data['body'] ? json_decode($data['body']) : "";
                 if (is_array($msg->error)) {
                     $msg = $msg->error[0];
                 } elseif ($msg->error) {
                     $msg = $msg->error;
                 } else {
                     $msg = "Unknown error. Error code: {$httpRequest->getResponseCode()}";
                 }
                 throw new Exception("Request to chef server failed with error: {$msg} ({$method} {$path})");
             } else {
                 throw new Exception("Unexpected situation. Response code {$httpRequest->getResponseCode()}");
             }
         }
     }
     return $retval;
 }
Esempio n. 19
0
<?php

$request = new HttpRequest();
$request->setUrl('https://exenzo.nl/api/v1/job/{job_id}');
$request->setMethod(HTTP_METH_PUT);
$request->setHeaders(array('cache-control' => 'no-cache', 'content-type' => 'application/json', 'x-authorization' => 'ORGANISATION-API-TOKEN'));
$request->setBody('{
    "name" : "Test Organisation Ltd",
    "image" : "iVBORw0KGgoAAAANSUhEUg....AElFTkSuQmCC"
}');
try {
    $response = $request->send();
    echo $response->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
 /**
  * Creates a new HTTP request. For use in conjunction with send(), e.g.:
  *
  * <code>
  *   $conn= new HttpConnection('http://example.com/');
  *   
  *   with ($request= $conn->create(new HttpRequest())); {
  *     $request->setMethod(HttpConstants::GET);
  *     $request->setParameters(array('a' => 'b'));
  *     $request->setHeader('X-Binford', '6100 (more power)');
  *
  *     $response= $conn->send($request);
  *     // ...
  *   }
  * </code>
  *
  * @param   peer.http.HttpRequest
  * @return  peer.http.HttpRequest request object
  */
 public function create(HttpRequest $r)
 {
     $r->setUrl(clone $this->url);
     return $r;
 }
Esempio n. 21
0
 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;
 }
Esempio n. 22
0
 /**
  * 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;
 }
Esempio n. 23
0
 public function statusAction()
 {
     $moduleParams['rabbitmq']['status'] = '';
     $moduleParams['rabbitmq']['showSetup'] = false;
     $moduleParams['rabbitmq']['showStatusLabel'] = true;
     $dbFarmRole = $this->getFarmRole();
     if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_URL)) {
         $serverId = $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_SERVER_ID);
         try {
             $dbServer = DBServer::LoadByID($serverId);
             if ($dbServer->status == SERVER_STATUS::RUNNING) {
                 $moduleParams['rabbitmq']['username'] = '******';
                 $moduleParams['rabbitmq']['password'] = $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_PASSWORD);
                 $moduleParams['rabbitmq']['url'] = "http://{$dbServer->remoteIp}:55672/mgmt/";
                 $url = str_replace('/mgmt/', '/api/overview', $moduleParams['rabbitmq']['url']);
                 $httpRequest = new HttpRequest();
                 $httpRequest->setUrl($url);
                 $httpRequest->setOptions(array('redirect' => 5, 'timeout' => 30, 'connecttimeout' => 10));
                 $httpRequest->setHeaders(array('Authorization' => 'Basic ' . base64_encode($moduleParams['rabbitmq']['username'] . ':' . $moduleParams['rabbitmq']['password'])));
                 $httpRequest->send();
                 $data = $httpRequest->getResponseData();
                 $result = json_decode($data['body'], true);
                 if ($result) {
                     $moduleParams['rabbitmq']['overview'] = $result;
                 }
             } else {
                 throw new \Scalr\Exception\ServerNotFoundException();
             }
         } catch (\Scalr\Exception\ServerNotFoundException $e) {
             $moduleParams['rabbitmq']['status'] = 'Control panel was installed, but server not found';
             $moduleParams['rabbitmq']['showSetup'] = true;
             $dbFarmRole->ClearSettings('rabbitmq.cp');
         } catch (Exception $e) {
             if (isset($e->innerException)) {
                 $msg = $e->innerException->getMessage();
             } else {
                 $msg = $e->getMessage();
             }
             $moduleParams['rabbitmq']['status'] = "Error retrieving information about control panel: \"{$msg}\"";
         }
     } else {
         if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUESTED) == '1') {
             if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_ERROR_MSG)) {
                 $moduleParams['rabbitmq']['showSetup'] = true;
                 $moduleParams['rabbitmq']['status'] = "Server return error: \"{$dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_ERROR_MSG)}\"";
             } else {
                 if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUEST_TIME) > time() - self::REQUEST_TIMEOUT) {
                     $moduleParams['rabbitmq']['status'] = "Request was sent at " . Scalr_Util_DateTime::convertTz((int) $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUEST_TIME)) . ". Please wait...";
                 } else {
                     $moduleParams['rabbitmq']['showSetup'] = true;
                     $moduleParams['rabbitmq']['status'] = "Request timeout exceeded. Request was sent at " . Scalr_Util_DateTime::convertTz((int) $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUEST_TIME));
                 }
             }
         } else {
             if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_PASSWORD)) {
                 $moduleParams['rabbitmq']['showSetup'] = true;
             } else {
                 $moduleParams['rabbitmq']['status'] = 'Rabbitmq cluster not initialized yet. Please wait ...';
                 $moduleParams['rabbitmq']['showStatusLabel'] = false;
             }
         }
     }
     $moduleParams['farmId'] = $dbFarmRole->FarmID;
     $moduleParams['rabbitmq']['password'] = $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_PASSWORD);
     $this->response->page('ui/services/rabbitmq/status.js', $moduleParams);
 }
Esempio n. 24
0
<?php

$request = new HttpRequest();
$request->setUrl('https://exenzo.nl/api/v1/organisation/{organisation_id}');
$request->setMethod(HTTP_METH_PUT);
$request->setHeaders(array('cache-control' => 'no-cache', 'content-type' => 'application/json', 'x-authorization' => 'ORGANISATION_API_TOKEN'));
$request->setBody('{
    "name" : "Test Organisation Ltd"
}');
try {
    $response = $request->send();
    echo $response->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
Esempio n. 25
0
 /**
  * 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());
     }
 }
Esempio n. 26
0
		/**
		 * 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;
            }
		}
Esempio n. 27
0
 public function head($url)
 {
     $request = new HttpRequest();
     $request->setMethod('HEAD');
     $request->setUrl($url);
     $this->doRequest($request);
 }
Esempio n. 28
0
 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;
 }
Esempio n. 29
0
<?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;
}
Esempio n. 30
0
 /**
  * @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;
 }