Ejemplo n.º 1
0
 protected function makeApiRequest($type, $action, $params, $format = null, $creds = null, $useCache = true)
 {
     $config = load_class('Config');
     $url = $config->config['base_url'] . 'api/' . urlencode($type);
     $useCache = false;
     // $creds === false means don't use credentials
     // $creds === null  means use default credentials
     // $creds === array($user, $pass) otherwise (where pass is md5)
     // TODO pull this from config or make default user
     if ($creds === null) {
         // TODO find a better solution here !!!
         if (!array_key_exists('api_creds_user', $config->config)) {
             $config->config['api_creds_user'] = '******';
         }
         if (!array_key_exists('api_creds_token', $config->config)) {
             $config->config['api_creds_token'] = '6228bd57c9a858eb305e0fd0694890f7';
         }
         $creds = array($config->config['api_creds_user'], $config->config['api_creds_token']);
     }
     $req = new StdClass();
     $req->request = new StdClass();
     if (is_array($creds)) {
         $req->request->auth = new StdClass();
         $req->request->auth->user = $creds[0];
         $req->request->auth->pass = $creds[1];
     }
     $req->request->action->type = $action;
     if (is_array($params)) {
         $req->request->action->data = new StdClass();
         foreach ($params as $k => $v) {
             $req->request->action->data->{$k} = $v;
         }
     }
     $payload = $this->encode_request($req, $format);
     $cache_filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'joindin-test-' . md5($url . $payload);
     if ($useCache) {
         // Check for reading from cache
         if (file_exists($cache_filename) && is_readable($cache_filename)) {
             $cache_data = json_decode(file_get_contents($cache_filename));
             if (time() < $cache_data->expires) {
                 return $cache_data->payload;
             }
         }
     }
     $request = new HttpRequest($url, HttpRequest::METH_POST);
     $request->setBody($payload);
     if ($format == 'xml') {
         $request->setHeaders(array('Content-Type' => 'text/xml'));
     } else {
         // json is the default
         $request->setHeaders(array('Content-Type' => 'application/json'));
     }
     $response = $request->send();
     if ($useCache) {
         $cache_data = json_encode(array('payload' => $response->getBody(), 'expires' => time() + 3600));
         file_put_contents($cache_filename, $cache_data);
         // chmod( $cache_filename, 0777 );
     }
     return $response->getBody();
 }
Ejemplo n.º 2
0
Archivo: Http.php Proyecto: kingsj/core
 /**
  * Send the request
  *
  * This function sends the actual request to the
  * remote/local webserver using pecl http
  *
  * @link http://us2.php.net/manual/en/http.request.options.php
  * @todo catch exceptions from HttpRequest and rethrow
  * @todo handle Puts
  */
 public function sendRequest()
 {
     $options = array('connecttimeout' => $this->requestTimeout);
     // if we have any listeners register an onprogress callback
     if (count($this->_listeners) > 0) {
         $options['onprogress'] = array($this, '_onprogress');
     }
     $tmp = 'HTTP_METH_' . strtoupper($this->verb);
     if (defined($tmp)) {
         $method = constant($tmp);
     } else {
         $method = HTTP_METH_GET;
     }
     $this->request = $request = new \HttpRequest($this->uri->url, $method, $options);
     $request->setHeaders($this->headers);
     if ($this->body) {
         $request->setRawPostData($this->body);
     }
     $request->send();
     $response = $request->getResponseMessage();
     $body = $response->getBody();
     $details = $this->uri->toArray();
     $details['code'] = $request->getResponseCode();
     $details['httpVersion'] = $response->getHttpVersion();
     $headers = new Request\Headers($response->getHeaders());
     $cookies = $request->getResponseCookies();
     return new Request\Response($details, $body, $headers, $cookies);
 }
Ejemplo 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());
         }
     }
 }
Ejemplo n.º 4
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);
     }
 }
Ejemplo n.º 5
0
function cb_get_pois($params)
{
    $base_addr = 'http://orion.lab.fi-ware.org:1026/v1/queryContext';
    $limit = 1000;
    try {
        $orion_key = json_decode(file_get_contents('../orion_key.txt'))[0];
    } catch (Exception $ex) {
        $orion_key = "";
    }
    $search_area = cb_search_area($params);
    $ans = array();
    $next = 0;
    $more = TRUE;
    try {
        while ($more) {
            $more = FALSE;
            $addr = $base_addr . '?';
            if ($next > 0) {
                $addr = $addr . 'offset=' . $next . '&';
            }
            $addr = $addr . 'limit=' . $limit;
            $next = $next + $limit;
            $http = new HttpRequest($addr, HTTP_METH_POST);
            $headers = array();
            $headers['Content-Type'] = 'application/json';
            $headers['Accept'] = 'application/json';
            if ($orion_key != "") {
                $headers['X-Auth-Token'] = $orion_key;
            }
            $http->setHeaders($headers);
            $body = '{"entities":[{"type":"cie_poi","isPattern":"true","id":"cie_poi_*' . '"}],"attributes":["data"],"restriction":{"scopes":[{"type":"FI' . 'WARE::Location","value":' . $search_area . '}]}}';
            $http->setBody($body);
            $respmsg = $http->send();
            $resp_str = $respmsg->getBody();
            $resp = json_decode($resp_str);
            if (property_exists($resp, 'contextResponses')) {
                $context_responses = $resp->contextResponses;
                foreach ($context_responses as $context_response) {
                    $more = TRUE;
                    $context_element = $context_response->contextElement;
                    $id = $context_element->id;
                    $uuid = substr($id, 8);
                    $attributes = $context_element->attributes;
                    foreach ($attributes as $attribute) {
                        $name = $attribute->name;
                        if ($name == 'data') {
                            $encoded_value = $attribute->value;
                            $json_value = rawurldecode($encoded_value);
                            $ans[$uuid] = json_decode($json_value, TRUE);
                        }
                    }
                }
            }
        }
    } catch (Exception $e) {
    }
    return $ans;
}
Ejemplo n.º 6
0
    public static function execute($parameters) {
      $h = new \HttpRequest($parameters['server']['scheme'] . '://' . $parameters['server']['host'] . $parameters['server']['path'] . (isset($parameters['server']['query']) ? '?' . $parameters['server']['query'] : ''), static::$_methods[$parameters['method']], array('redirect' => 5));

      if ( isset($parameters['header']) ) {
        $headers = array();

        foreach ( $parameters['header'] as $header ) {
          list($key, $value) = explode(':', $header, 2);

          $headers[$key] = trim($value);
        }

        $h->setHeaders($headers);
      }

      if ( $parameters['method'] == 'post' ) {
        $h->setBody($parameters['parameters']);
      }

      if ( $parameters['server']['scheme'] === 'https' ) {
        $h->addSslOptions(array('verifypeer' => true,
                                'verifyhost' => true));

        if ( isset($parameters['cafile']) && file_exists($parameters['cafile']) ) {
          $h->addSslOptions(array('cainfo' => $parameters['cafile']));
        }

        if ( isset($parameters['certificate']) ) {
          $h->addSslOptions(array('cert' => $parameters['certificate']));
        }
      }

      $result = '';

      try {
        $h->send();

        $result = $h->getResponseBody();
      } catch ( \Exception $e ) {
        if ( isset($e->innerException) ) {
          trigger_error($e->innerException->getMessage());
        } else {
          trigger_error($e->getMessage());
        }
      }

      return $result;
    }
Ejemplo n.º 7
0
 protected function makeApiRequest($type, $action, $params, $creds = null, $useCache = true)
 {
     // $creds === false means don't use credentials
     // $creds === null  means use default credentials
     // $creds === array($user, $pass) otherwise
     if ($creds === null) {
         $creds = array('kevin', '6228bd57c9a858eb305e0fd0694890f7');
     }
     $url = "http://lorna.rivendell.local/api/" . urlencode($type);
     $req = new StdClass();
     $req->request = new StdClass();
     if (is_array($creds)) {
         $req->request->auth = new StdClass();
         $req->request->auth->user = $creds[0];
         $req->request->auth->pass = $creds[1];
     }
     $req->request->action->type = $action;
     if (is_array($params)) {
         $req->request->action->data = new StdClass();
         foreach ($params as $k => $v) {
             $req->request->action->data->{$k} = $v;
         }
     }
     $payload = json_encode($req);
     $cache_filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'joindin-test-' . md5($url . $payload);
     if ($useCache) {
         // Check for reading from cache
         if (file_exists($cache_filename) && is_readable($cache_filename)) {
             $cache_data = json_decode(file_get_contents($cache_filename));
             if (time() < $cache_data->expires) {
                 return $cache_data->payload;
             }
         }
     }
     $request = new HttpRequest($url, HttpRequest::METH_POST);
     $request->addRawPostData($payload);
     $request->setHeaders(array('Content-Type' => 'application/json'));
     $response = $request->send();
     if ($useCache) {
         $cache_data = json_encode(array('payload' => $response->getBody(), 'expires' => time() + 3600));
         file_put_contents($cache_filename, $cache_data);
         chmod($cache_filename, 0777);
     }
     return $response->getBody();
 }
Ejemplo n.º 8
0
 function request($url, $options = array())
 {
     $url = "http://" . $this->host . ":" . $this->port . $url;
     $method = HTTP_METH_GET;
     $headers = array("Host" => $this->host, "Referer" => "http://localhost/", "Content-Type" => "application/json");
     $params = '';
     foreach ($options as $name => $option) {
         switch ($name) {
             case "method":
                 $method = $option;
                 break;
             case "headers":
                 $headers = array_merge($option, $headers);
                 break;
             case "params":
                 $params = http_build_query($option);
                 break;
             case "postdata":
                 $post_data = $option;
                 break;
             default:
                 trigger_error("Unknown http option: {$name}", E_USER_WARNING);
         }
     }
     if (!empty($params)) {
         $url = $url . "?" . $params;
     }
     $request = new HttpRequest($url, $method);
     $request->setHeaders($headers);
     if (isset($post_data)) {
         if ($method == HTTP_METH_PUT) {
             $request->addPutData($post_data);
         } else {
             if ($method == HTTP_METH_POST) {
                 $request->setRawPostData($post_data);
             }
         }
     }
     $json = $request->send()->getBody();
     $data = json_decode($json, true);
     if (isset($data['rows'])) {
         $data = new CouchResult($data);
     }
     return $data;
 }
Ejemplo n.º 9
0
 private function request($method, Object $params = null)
 {
     $requestObj = new stdClass();
     $requestObj->id = microtime(true);
     $requestObj->method = $method;
     $requestObj->params = $params;
     $jsonRequest = json_encode($requestObj);
     $timestamp = date("D d M Y H:i:s T");
     $dt = new DateTime($timestamp, new DateTimeZone("CDT"));
     $timestamp = Scalr_Util_DateTime::convertDateTime($dt, new DateTimeZone("UTC"), new DateTimeZone("CDT"))->format("D d M Y H:i:s");
     $timestamp .= " UTC";
     $canonical_string = $jsonRequest . $timestamp;
     $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 1));
     $request = new HttpRequest("http://{$this->dbServer->remoteIp}:{$this->port}/", HTTP_METH_POST);
     $request->setOptions(array('timeout' => 5, 'connecttimeout' => 5));
     $request->setHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId));
     $request->setRawPostData($jsonRequest);
     try {
         // Send request
         $request->send();
         if ($request->getResponseCode() == 200) {
             $response = $request->getResponseData();
             $jResponse = @json_decode($response['body']);
             if ($jResponse->error) {
                 throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data}");
             }
             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));
     }
 }
Ejemplo n.º 10
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;
 }
Ejemplo n.º 11
0
<?php

$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_POST);
$request->setQueryData(array('foo' => array('bar', 'baz'), 'baz' => 'abc', 'key' => 'value'));
$request->setHeaders(array('content-type' => 'application/x-www-form-urlencoded', 'accept' => 'application/json'));
$request->setCookies(array('bar' => 'baz', 'foo' => 'bar'));
$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array('foo' => 'bar'));
try {
    $response = $request->send();
    echo $response->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
Ejemplo n.º 12
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;
 }
<?php

$url = 'http://localhost/book/put-form-page.php';
$data = array("email" => "*****@*****.**", "display_name" => "LornaJane");
$request = new HttpRequest($url, HTTP_METH_PUT);
$request->setHeaders(array("Content-Type" => "application/x-www-form-urlencoded"));
$request->setPutData(http_build_query($data));
$request->send();
$page = $request->getResponseBody();
echo $page;
Ejemplo n.º 14
0
<?php

$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array('content-type' => 'text/plain'));
$request->setBody('Hello World');
try {
    $response = $request->send();
    echo $response->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
Ejemplo n.º 15
0
     }
     foreach (array_keys($data) as $uuid) {
         //             print $uuid;
         $comp_data = getComponentMongoDB($mongodb, $component, $uuid, $fetch_for_update);
         if ($comp_data != NULL) {
             $data[$uuid][$component] = $comp_data;
         }
     }
 }
 // additional pois and fields from context broker
 $entities = array();
 foreach ($data as $poi_uuid => $poi_data) {
     $entities[] = ['type' => 'cie_poi', 'isPattern' => 'false', 'id' => 'cie_poi_' . $uuid];
 }
 $http = new HttpRequest($addr, HTTP_METH_POST);
 $http->setHeaders(array('Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => 'RxfRG8jXhUwic0Mz56k8hv-mf3ZDnQ79JJkX2fVLa0jwCL0QJ' . 'tx9ML-htbnMEwU0jqn4KJ2WyXoWmZYnnfF5Ug'));
 $body = '{"entities":' . json_encode($entities) . ',"attributes":["data"]}';
 $http->setBody($body);
 $respmsg = $http->send();
 $resp_str = $respmsg->getBody();
 $resp = json_decode($resp_str);
 if (property_exists($resp, 'contextResponses')) {
     $context_responses = $resp->contextResponses;
     foreach ($context_responses as $context_response) {
         $more = TRUE;
         $context_element = $context_response->contextElement;
         $id = $context_element->id;
         $uuid = substr($id, 8);
         $attributes = $context_element->attributes;
         foreach ($attributes as $attribute) {
             $name = $attribute->name;
Ejemplo n.º 16
0
 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;
 }
function executeAsrRequest($url, $header, $audio)
{
    // First, we need to set a few SSL options
    $sslOptions = array();
    $sslOptions['verifypeer'] = "0";
    $sslOptions['verifyhost'] = "0";
    // Create an HttpRequest object
    $r = new HttpRequest($url, HttpRequest::METH_POST);
    // Set the SSL options, Headers, Content-Type, and body
    $r->setSslOptions($sslOptions);
    $r->setHeaders($header);
    $r->setContentType($header['Content-Type']);
    $r->setBody($audio);
    try {
        // Send the request
        $m = $r->send();
        // Return the response object
        return $m;
    } catch (HttpException $ex) {
        // If an error occurs, just display it to the web page
        echo '<br><br><font color="red" Exception: ' . $ex . '</font><br><br>';
    }
}
<html>
    <head></head>
    <body>
        <?php 
$r = new HttpRequest('http://www.webservicex.net/globalweather.asmx', HttpRequest::METH_POST);
//set headers
$arrayHeadeFields = array("Host" => "www.webservicex.net", "SOAPAction" => "http://www.webserviceX.NET/GetWeather");
$r->setContentType("text/xml; charset=utf-8");
$r->setHeaders($arrayHeaderFields);
//set the soap message for the request
$xmlSoapMessage = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetWeather xmlns="http://www.webserviceX.NET">
<CityName>singapore</CityName>
<CountryName>singapore</CountryName>
</GetWeather>
</soap:Body>
</soap:Envelope>';
$r->setBody($xmlSoapMessage);
try {
    $r->send();
    echo '<h2>Request Header</h2>';
    echo '<pre>';
    print_r($r->getRawRequestMessage());
    echo '</pre>';
    $responseCode = $r->getResponseCode();
    $responseHeader = $r->getResponseHeader();
    $responseBody = $r->getResponseBody();
    echo '--------------------------------------------------------------------------------------------<br/>';
    echo '<h2>Rseponse Code</h2>';
Ejemplo n.º 19
0
function update_orion()
{
    $now = date('Y-m-d G:i:s');
    $msg = $now . "\n";
    try {
        $orion_key = json_decode(file_get_contents('../orion_key.txt'))[0];
    } catch (Exception $ex) {
        $orion_key = "";
    }
    try {
        $oldpois = json_decode(file_get_contents('pois.txt'), TRUE);
    } catch (Exception $ex) {
        $oldpois = array();
    }
    $newpois = array();
    $content = file_get_contents(POI_SERVER);
    $response_structure = json_decode($content, TRUE);
    $pois = $response_structure['pois'];
    $poicnt = 0;
    $more = TRUE;
    while ($more) {
        $more = FALSE;
        $contextElements = '{"contextElements":[' . "\n";
        foreach ($pois as $uuid => $data) {
            if (!isset($newpois[$uuid])) {
                $json_data = json_encode($data);
                $encoded_data = rawurlencode($json_data);
                $lat = $data['fw_core']['location']['wgs84']['latitude'];
                $lon = $data['fw_core']['location']['wgs84']['longitude'];
                if (strlen($contextElements) < 1000000) {
                    $newpois[$uuid] = 1;
                    $contextElements .= '{' . '"type": "cie_poi",' . '"isPattern": "false",' . '"id": "cie_poi_' . $uuid . '",' . '"attributes": [' . '{ "name": "data",' . '"type": "string",' . '"value": "' . $encoded_data . '"' . '},' . '{' . '"name": "position",' . '"type": "coords",' . '"value": "' . $lat . ', ' . $lon . '",' . '"metadatas": [' . '{' . '"name": "location",' . '"type": "string",' . '"value": "WGS84"' . '}]}]},' . "\n";
                    $poicnt++;
                    $more = TRUE;
                }
            }
        }
        if ($more) {
            $contextElements = substr($contextElements, 0, strrpos($contextElements, ',')) . '],"updateAction":"APPEND"}';
            $r = new HttpRequest(restBaseURL . 'updateContext', HttpRequest::METH_POST);
            $r->setContentType('application/json');
            $headers = array();
            $headers['Content-Type'] = 'application/json';
            $headers['Accept'] = 'application/json';
            if ($orion_key != "") {
                $headers['X-Auth-Token'] = $orion_key;
            }
            $r->setHeaders($headers);
            $r->addRawPostData($contextElements);
            try {
                $r->send();
                $status = $r->getResponseBody();
                if (strpos($status, '"errorCode"')) {
                    $msg .= $status . "\n";
                }
            } catch (HttpException $ex) {
                $msg .= "ERROR\n" . $ex . "\n";
            }
        }
    }
    if ($poicnt > 0) {
        // delete disappeared pois
        $deletecnt = 0;
        foreach ($oldpois as $uuid => $x) {
            if (!isset($newpois[$uuid])) {
                $deletecnt++;
                $r = new HttpRequest(restBaseURL . "contextEntities/cie_poi_" . $uuid, HttpRequest::METH_DELETE);
                $r->setContentType('application/json');
                $headers = array();
                $headers['Content-Type'] = 'application/json';
                $headers['Accept'] = 'application/json';
                if ($orion_key != "") {
                    $headers['X-Auth-Token'] = $orion_key;
                }
                $r->setHeaders($headers);
                try {
                    $r->send();
                    $resp_str = $r->getResponseBody();
                    $resp = json_decode($resp_str, TRUE);
                    $code = "?";
                    foreach ($resp as $key => $info) {
                        if ($key == 'code') {
                            $code = $info;
                        } else {
                            if (isset($info['code'])) {
                                $code = $info['code'];
                            }
                        }
                    }
                    // OK if 200 (OK) or 404 (not found)
                    if ($code != "200" && $code != "404") {
                        $newpois[$uuid] = 2;
                        $msg .= "Failed to delete {$uuid}\n({$code}) {$resp_str}\n";
                    }
                } catch (Exception $ex) {
                    $newpois[$uuid] = 3;
                    $msg .= "Failed to delete {$uuid}\nException: {$ex}\n";
                }
            }
        }
        // save current poi list
        file_put_contents('pois.txt', json_encode($newpois));
    } else {
        $msg .= "No data\n" . $content . "\n";
    }
    file_put_contents('status.txt', $msg);
}
Ejemplo n.º 20
0
 protected function sendRequest($uri, $method, $data = null)
 {
     try {
         $request = new HttpRequest("https://{$this->active_domain}.chargify.com{$uri}");
         $request->setHeaders(array('Content-Type' => 'application/xml'));
         $request->setOptions(array('httpauth' => "{$this->active_api_key}:x", 'timeout' => 45, 'connecttimeout' => 45));
         $request->setMethod(constant("HTTP_METH_{$method}"));
         if ($data) {
             $request->setRawPostData($data);
         }
     } catch (Exception $e) {
         //TODO:
         throw $e;
     }
     $request->send();
     return $request;
 }
Ejemplo n.º 21
0
<?php

$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array('content-type' => 'application/json'));
$request->setBody('{"number":1,"string":"f\\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}]}');
try {
    $response = $request->send();
    echo $response->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
Ejemplo n.º 22
0
<?php

$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_GET);
$request->setHeaders(array('x-foo' => 'Bar', 'accept' => 'application/json'));
try {
    $response = $request->send();
    echo $response->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
Ejemplo n.º 23
0
 /**
  *
  * 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;
 }
Ejemplo n.º 24
0
}
#$r = new HttpRequest('https://gd2.line.naver.jp/' . $_SERVER['REQUEST_URI'], HttpRequest::METH_POST);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $r = new HttpRequest($u, HttpRequest::METH_POST);
    $r->addPostFields($_POST);
} else {
    $r = new HttpRequest($u, HttpRequest::METH_GET);
}
$r->setOptions(array('cookies' => $_COOKIE, 'proxyhost' => 'localhost', 'proxyport' => 8088, 'proxytype' => HTTP_PROXY_HTTP));
$hdr = array();
foreach (getallheaders() as $key => $val) {
    $hdr[$key] = $val;
}
unset($hdr['Accept-Encoding']);
$hdr['Content-Type'] = "application/x-thrift";
$r->setHeaders($hdr);
$content = $HTTP_RAW_POST_DATA;
if ($hijacking_mode == 1 and strrpos($content, "loginWithIdentityCredentialForCertificate_disabled")) {
    $flag_login = 1;
    $debug_file = "line.log";
    $fp = fopen($debug_file, 'a');
    fwrite($fp, date('Y-m-d H:i:s'));
    fwrite($fp, "\n");
    // if login process,
    // retrieve original data
    fwrite($fp, sprintf("content = %s\n", $content));
    $pattern = '/[a-z0-9]{202}/';
    // the wrapped preg_match call
    if (preg_match($pattern, $content, $matches)) {
        // fwrite($fp, sprintf("matches = %s\n", var_dump($matches, true)));
        $mitm_rsa = $matches[0];
Ejemplo n.º 25
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;
}
Ejemplo n.º 26
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);
 }
Ejemplo n.º 27
0
 /**
  *
  * 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;
 }
Ejemplo n.º 28
0
 /**
  * Creates a request.
  *
  * @param string $url Request URL
  * @param integer $method Request method
  * @param array $headers Array of headers
  * @return \HttpRequest
  */
 private function getRequest($url, $method, array $headers = array())
 {
     $request = new \HttpRequest($url, $method, $this->options);
     $request->setHeaders(array('Expect' => ''));
     $request->addHeaders($headers);
     return $request;
 }
Ejemplo n.º 29
0
<?php

$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array('content-type' => 'multipart/form-data; boundary=---011000010111000001101001'));
$request->setBody('-----011000010111000001101001
Content-Disposition: form-data; name="foo"; filename="hello.txt"
Content-Type: text/plain


-----011000010111000001101001--');
try {
    $response = $request->send();
    echo $response->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
Ejemplo n.º 30
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)
 {
     if ($this->farmId) {
         if ($this->GetFarmObject()->Status == FARM_STATUS::TERMINATED) {
             $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::FAILED, $message->messageId));
             return;
         }
     }
     $logger = Logger::getLogger('DBServer');
     $serializer = Scalr_Messaging_XmlSerializer::getInstance();
     $cryptoTool = Scalr_Messaging_CryptoTool::getInstance();
     $rawMessage = $serializer->serialize($message);
     // Add message to database
     $this->Db->Execute("INSERT INTO messages SET\r\n\t\t\t\t`messageid`\t= ?,\r\n\t\t\t\t`server_id`\t= ?,\r\n\t\t\t\t`message`\t= ?,\r\n\t\t\t\t`type`\t\t= 'out',\r\n\t\t\t\t`message_name` = ?,\r\n\t\t\t\t`handle_attempts` = ?,\r\n\t\t\t\t`message_version` = ?,\r\n\t\t\t\t`dtlasthandleattempt` = NOW()\r\n\t\t\tON DUPLICATE KEY UPDATE handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW()  \r\n\t\t\t", array($message->messageId, $this->serverId, $rawMessage, $message->getName(), $delayed ? '0' : '1', $this->IsSupported("0.5") ? 2 : 1));
     if ($this->platform == SERVER_PLATFORMS::RDS) {
         $logger->info("RDS platform doesn't support messaging. Skipping...");
         $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::UNSUPPORTED, $message->messageId));
         return $message;
     }
     if ($delayed) {
         return $message;
     }
     if ($this->IsSupported("0.5") && !$isEventNotice) {
         if (!$this->remoteIp) {
             return;
         }
         // Put access data and reserialize message
         $pl = PlatformFactory::NewPlatform($this->platform);
         $pl->PutAccessData($this, $message);
         $rawMessage = $serializer->serialize($message);
         $cryptoKey = $this->GetKey(true);
         $encMessage = $cryptoTool->encrypt($rawMessage, $cryptoKey);
         list($signature, $timestamp) = $cryptoTool->sign($encMessage, $cryptoKey);
         try {
             $ctrlPort = $this->GetProperty(SERVER_PROPERTIES::SZR_CTRL_PORT);
             if (!$ctrlPort) {
                 $ctrlPort = 8013;
             }
             // Prepare request
             $request = new HttpRequest("http://{$this->remoteIp}:{$ctrlPort}/control", HTTP_METH_POST);
             $request->setOptions(array('timeout' => 4, 'connecttimeout' => 4));
             $request->setHeaders(array("Date" => $timestamp, "X-Signature" => $signature));
             $request->setRawPostData($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) complete", $this->farmId, $message->getName(), $this->remoteIp, $this->serverId));
                 $this->Db->Execute("UPDATE messages SET status = ?, message = '' WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId));
             } 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)));
             } 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;
         }
     } else {
         if ($this->remoteIp) {
             $community = $this->Db->GetOne("SELECT hash FROM farms WHERE id=?", array($this->farmId));
             $snmpClient = new Scalr_Net_Snmp_Client();
             $snmpClient->connect($this->remoteIp, 162, $community);
             $converter = Scalr_Messaging_SnmpConverter::getInstance();
             $trap = $converter->convert($message, $isEventNotice);
             $res = $snmpClient->sendTrap($trap);
             Logger::getLogger('DBServer')->info("[FarmID: {$this->farmId}] Sending message " . $message->getName() . " via SNMP ({$trap}) to '{$this->serverId}' ('{$this->remoteIp}') complete ({$res})");
         }
     }
     return $message;
 }