Exemplo n.º 1
0
 private function http2_request($method, $path, $params)
 {
     $url = $this->api . rtrim($path, '/') . '/';
     if (!strcmp($method, "POST")) {
         $req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
         $req->setHeader('Content-type: application/json');
         if ($params) {
             $req->setBody(json_encode($params));
         }
     } else {
         if (!strcmp($method, "GET")) {
             $req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
             $url = $req->getUrl();
             $url->setQueryVariables($params);
         } else {
             if (!strcmp($method, "DELETE")) {
                 $req = new HTTP_Request2($url, HTTP_Request2::METHOD_DELETE);
                 $url = $req->getUrl();
                 $url->setQueryVariables($params);
             }
         }
     }
     $req->setAdapter('curl');
     $req->setConfig(array('timeout' => 30, 'ssl_verify_peer' => FALSE));
     $req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
     $req->setHeader(array('Connection' => 'close', 'User-Agent' => 'PHPPlivo'));
     $r = $req->send();
     $status = $r->getStatus();
     $body = $r->getbody();
     $response = json_decode($body, true);
     return array("status" => $status, "response" => $response);
 }
Exemplo n.º 2
0
 public function OXreqPUTforSendMail($url, $QueryVariables, $PutData, $returnResponseObject = false)
 {
     $QueryVariables['timezone'] = 'UTC';
     # all times are UTC,
     $request = new HTTP_Request2(OX_SERVER . $url, HTTP_Request2::METHOD_PUT);
     $request->setHeader('Content-type: text/javascript; charset=utf-8');
     $url = $request->getUrl();
     $url->setQueryVariables($QueryVariables);
     $request->setBody(utf8_encode($PutData));
     return $this->OXreq($request, $returnResponseObject);
 }
Exemplo n.º 3
0
 /**
  * Make an API request.
  *
  * @param string $url    The URL to request agains.
  * @param string $method The request method.
  * @param mixed  $data   Optional, most likely a json encoded string.
  *
  * @return HTTP_Request2_Response
  * @throws HTTP_Request2_Exception In case something goes wrong. ;)
  */
 protected function makeRequest($url, $method = HTTP_Request2::METHOD_GET, $data = null)
 {
     if ($this->apiToken !== null) {
         $url .= '?u=' . $this->apiToken;
     }
     if (!$this->client instanceof HTTP_Request2) {
         $this->client = new HTTP_Request2();
     }
     $this->client->setHeader('Content-Type: application/json')->setAuth($this->username, $this->password)->setMethod($method)->setUrl($this->endpoint . $url);
     if ($data !== null) {
         $this->client->setBody($data);
     }
     $resp = $this->client->send();
     return $resp;
 }
 /**
  * 記事を投稿する.
  *
  * @param string $title 記事タイトル
  * @param string $text 記事本文
  * @param string $category 記事カテゴリ
  * @return string $res 結果
  */
 public function postArticle($title, $text, $category)
 {
     try {
         $req = new HTTP_Request2();
         $req->setUrl(self::ROOT_END_POINT . $this->liveDoorId . "/" . self::END_POINT_TYPE_ARTICLE);
         $req->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false));
         $req->setMethod(HTTP_Request2::METHOD_POST);
         $req->setAuth($this->liveDoorId, $this->atomPubPassword);
         $req->setBody($this->createBody($title, $text, $category));
         $req->setHeader('Expect', '');
         $res = $req->send();
     } catch (HTTP_Request2_Exception $e) {
         die($e->getMessage());
     } catch (Exception $e) {
         die($e->getMessage());
     }
     return $res;
 }
Exemplo n.º 5
0
 function update($acct, Link $link, Link $newlink)
 {
     $request = new HTTP_Request2($this->url, HTTP_Request2::METHOD_PUT);
     $request->setHeader($this->headers);
     $query = $link->toArray();
     $query['acct'] = $acct;
     $request->getUrl()->setQueryVariables($query);
     $request->setBody($newlink->toTag());
     try {
         $response = $request->send();
         if (200 == $response->getStatus()) {
             return $response->getBody();
         } else {
             echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' . $response->getReasonPhrase();
             return null;
         }
     } catch (HTTP_Request2_Exception $e) {
         echo 'Error: ' . $e->getMessage();
     }
 }
Exemplo n.º 6
0
 private function http2_request($method, $path, $params)
 {
     $url = $this->api . $path;
     $http_method = \HTTP_Request2::METHOD_POST;
     if (!strcmp($method, "GET")) {
         $http_method = \HTTP_Request2::METHOD_GET;
     } else {
         if (!strcmp($method, "DELETE")) {
             $http_method = \HTTP_Request2::METHOD_DELETE;
         }
     }
     $req = new \HTTP_Request2($url, $http_method);
     if ($http_method === \HTTP_Request2::METHOD_POST && $params) {
         $req->setBody(json_encode($params));
     }
     $req->setAdapter('curl');
     $req->setConfig(array('timeout' => 30, 'ssl_verify_peer' => FALSE));
     $req->setHeader(array('Authorization' => $this->auth_token, 'Connection' => 'close', 'User-Agent' => 'CheckMobi/http2_request', 'Content-type' => 'application/json'));
     $r = $req->send();
     $status = $r->getStatus();
     $body = $r->getbody();
     $response = json_decode($body, true);
     return array("status" => $status, "response" => $response);
 }
Exemplo n.º 7
0
 public function _getResponse(S3 $s3, $url, $headers, $amz)
 {
     $req = new HTTP_Request2($url, $this->verb);
     if (!$s3->useSSLValidation) {
         $req->setConfig('ssl_verify_host', false);
         $req->setConfig('ssl_verify_peer', false);
     }
     if ($s3->proxy != null && isset($s3->proxy['host'])) {
         $req->setConfig('proxy_host');
         $req->setConfig('proxy_host', $s3->proxy['host']);
         if (isset($s3->proxy['user'], $s3->proxy['pass']) && $proxy['user'] != null && $proxy['pass'] != null) {
             $req->setConfig('proxy_user', $s3->proxy['user']);
             $req->setConfig('proxy_password', $s3->proxy['pass']);
         }
     }
     if ($s3->hasAuth()) {
         // Authorization string (CloudFront stringToSign should only contain a date)
         $headers[] = 'Authorization: ' . $s3->__getSignature($this->headers['Host'] == 'cloudfront.amazonaws.com' ? $this->headers['Date'] : $this->verb . "\n" . $this->headers['Content-MD5'] . "\n" . $this->headers['Content-Type'] . "\n" . $this->headers['Date'] . $amz . "\n" . $this->resource);
     }
     $req->setHeader($headers);
     $req->setConfig('follow_redirects', true);
     // Request types
     switch ($this->verb) {
         case 'GET':
             break;
         case 'PUT':
         case 'POST':
             // POST only used for CloudFront
             if ($this->fp !== false) {
                 $req->setBody($this->fp);
             } elseif ($this->data !== false) {
                 $req->setBody($this->data);
             }
             break;
     }
     try {
         $res = $req->send();
     } catch (HTTP_Request2_Exception $e) {
         $this->response->error = array('code' => $e->getCode(), 'message' => $e->getMessage(), 'resource' => $this->resource);
     }
     $this->response->code = $res->getStatus();
     $this->response->body = $res->getBody();
     $this->response->headers = $this->modHeaders($res->getHeader());
     return $this->response;
 }
Exemplo n.º 8
0
*/
//openssl smime -sign -signer certnew_Vaan.cer -nochain -nocerts -outform PEM -nodetach
//openssl.exe smime -sign -signer public.pem -inkey private.pem -nochain -nocerts -outform PEM -nodetach
$request = new HTTP_Request2($url);
//$request->setMethod(HTTP_Request2::METHOD_POST);
/*
$request->setConfig(array(
    'ssl_verify_peer'   => FALSE,
    'ssl_verify_host'   => FALSE
    
    //'ssl_verify_peer' => TRUE,
    //'ssl_local_cert' => 'ym.p7b'
));
*/
$request->setHeader($parts[0]);
$request->setBody($parts[1]);
//$request->addUpload($url, $headers_msg, $sendFilename, $contentType);
//$request->s
//$request->getHeaders();
$response = $request->send();
var_dump($response->getStatus());
/*
$request->setMethod(HTTP_Request2::METHOD_POST)
    ->addPostParameter('username', 'vassily')
    ->addPostParameter(array(
        'email' => '*****@*****.**',
        'phone' => '+7 (495) 123-45-67'
    ))
    ->addUpload('avatar', './exploit.exe', 'me_and_my_cat.jpg', 'image/jpeg');
*/
//$test = new COM();
Exemplo n.º 9
0
    // リクエスト作成
    $request = new HTTP_Request2();
    $request->setHeader($header);
    $request->setUrl($url);
    if ($method == 'GET') {
        $request->setMethod(HTTP_Request2::METHOD_GET);
    } elseif ($method == 'POST') {
        $request->setMethod(HTTP_Request2::METHOD_POST);
    } elseif ($method == 'PUT') {
        $request->setMethod(HTTP_Request2::METHOD_PUT);
    } elseif ($method == 'DELETE') {
        $request->setMethod(HTTP_Request2::METHOD_DELETE);
    } else {
        die;
    }
    $request->setBody(trim($body));
    $request->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false));
    // レスポンス取得
    $response = $request->send();
    // HTTP_Request2のエラーを表示
} catch (HTTP_Request2_Exception $e) {
    die($e->getMessage());
    // それ以外のエラーを表示
} catch (Exception $e) {
    die($e->getMessage());
}
// エラー時
if ($response->getStatus() != "200") {
    echo "{";
    echo sprintf("\"httpStatus\":\"%s\"", $response->getStatus());
    echo ",";
Exemplo n.º 10
0
}
// @see http://xpoint.ru/forums/programming/PHP/faq.xhtml#740
if (!empty($GLOBALS['HTTP_RAW_POST_DATA'])) {
    $body = $GLOBALS['HTTP_RAW_POST_DATA'];
    if ($Config['Log-Mode'] >= 2 && $Config['Log-Path']) {
        for ($i = 1; $i <= 200; ++$i) {
            $fname = date('Ymd-His') . '-I-' . $i . '.html';
            if (!file_exists($fname)) {
                $fp = fopen($Config['Log-Path'] . '/' . $fname, 'w');
                fwrite($fp, $body);
                fclose($fp);
                break;
            }
        }
    }
    $request->setBody($body);
}
$resp = $request->send();
$headers = $resp->getHeader();
if ($Config['Log-Mode']) {
    $log[] = '--------------------------';
    $log[] = '<<||<< ' . date('Y-m-d H:i:s');
    $log[] = '--------------------------';
    foreach ($headers as $name => $value) {
        $log[] = $name . ': ' . $value;
    }
}
$headers = exclude($headers, $Config['Head-Out-Exclude']);
foreach ($headers as $name => $value) {
    header("{$name}: {$value}");
}
Exemplo n.º 11
0
 /**
  * Send data to CouchDB. This function dies on HTTP error and also if no
  * config.ini is found.
  *
  * @param array  $data  The object/document.
  * @param string $file  The filename of the log currently being crunched.
  * @param int    $count Which line are we at?
  *
  * @return void
  * @uses   \HTTP_Request2
  */
 public static function sendToCouchDb(array $data, $file, $count)
 {
     static $config;
     if ($config === null) {
         $config = parse_ini_file(self::$base . '/config.ini', true);
         if ($config === false) {
             echo "Couldn't read config.ini.";
             exit(1);
         }
     }
     static $req;
     if ($req === null) {
         require_once 'HTTP/Request2.php';
         $req = new \HTTP_Request2();
         $req->setAuth($config['couchdb']['user'], $config['couchdb']['pass']);
         $req->setMethod(\HTTP_Request2::METHOD_PUT);
     }
     $obj = (object) $data;
     $id = md5($obj->line);
     // generate _id
     try {
         $req->setUrl($config['couchdb']['host'] . "/{$id}");
         $req->setBody(json_encode($obj));
         $resp = $req->send();
         echo "\tDocument: {$id} (file: {$file}, line: {$count}), ";
         echo "Response: " . $resp->getStatus();
         if ($resp->getStatus() == 409) {
             echo " [duplicate]";
         }
         echo "\n";
         unset($resp);
         unset($obj);
         unset($data);
         unset($id);
     } catch (Exception $e) {
         echo "Error: " . $e->getMessage();
         exit(1);
     }
 }
Exemplo n.º 12
0
 /**
  * Sets the request body.
  * 
  * @param string $body body to use.
  * 
  * @return none
  */
 public function setBody($body)
 {
     Validate::isString($body, 'body');
     $this->_request->setBody($body);
 }
    public function _fetch_by_options()
    {
        $method = 'Bug.search';
        $struct = '';
        foreach ($this->options as $k => $v) {
            $struct .= sprintf('<member><name>%s</name><value><%s>%s</%s></value></member>' . "\n", $k, 'string', $v, 'string');
        }
        $xml = <<<X
<?xml version="1.0" encoding="utf-8"?>
<methodCall>
    <methodName>{$method}</methodName>
    <params>
        <param>
            <struct>
                {$struct}
            </struct>
        </param>
    </params>
</methodCall>
X;
        $request = new HTTP_Request2($this->url, HTTP_Request2::METHOD_POST, array('follow_redirects' => true, 'ssl_verify_peer' => false));
        $request->setHeader('Accept', 'text/xml');
        $request->setHeader('Content-Type', 'text/xml;charset=utf-8');
        $request->setBody($xml);
        try {
            $response = $request->send();
            if (200 == $response->getStatus()) {
                $x = simplexml_load_string($response->getBody());
                $this->data['bugs'] = array();
                // FIXME there must be a better way
                foreach ($x->params->param->value->struct->member->value->array->data->value as $b) {
                    $bug = array();
                    foreach ($b->struct->member as $m) {
                        if ($m->name == 'internals') {
                            continue;
                        }
                        $value = (array) $m->value;
                        $bug[(string) $m->name] = (string) array_shift($value);
                    }
                    $this->data['bugs'][] = $bug;
                }
            } else {
                $this->error = 'Server returned unexpected HTTP status: ' . $response->getStatus() . ' ' . $response->getReasonPhrase();
                return;
            }
        } catch (HTTP_Request2_Exception $e) {
            $this->error = $e->getMessage();
            return;
        }
        if (isset($this->data['error']) && !empty($this->data['error'])) {
            $this->error = "Bugzilla API returned an error: " . $this->data['message'];
        }
    }
Exemplo n.º 14
0
 /**
  * we use the Pear::\HTTP_Request2 for all the heavy HTTP protocol lifting.
  *
  * @param string $resource api-resource
  * @param string $method request method [default:"GET"]
  * @param array $data request data as associative array [default:array()]
  * @param array $headers optional request header [default:array()]
  *
  * @throws ConnectionException
  * @throws BadRequestError
  * @throws UnauthorizedError
  * @throws ForbiddenError
  * @throws ConflictDuplicateError
  * @throws GoneError
  * @throws InternalServerError
  * @throws NotImplementedError
  * @throws ThrottledError
  * @throws CCException
  *
  * @return string json encoded servers response
  */
 private function _request($resource, $method = \HTTP_Request2::METHOD_GET, $data = array(), $headers = array())
 {
     $url = $this->_url . $resource;
     $request = new \HTTP_Request2($url);
     $request->setConfig(array('ssl_verify_peer' => API::SSL_VERIFY_PEER, 'ssl_cafile' => realpath(dirname(__FILE__)) . '/cacert.pem'));
     $methods = array('options' => \HTTP_Request2::METHOD_OPTIONS, 'get' => \HTTP_Request2::METHOD_GET, 'head' => \HTTP_Request2::METHOD_HEAD, 'post' => \HTTP_Request2::METHOD_POST, 'put' => \HTTP_Request2::METHOD_PUT, 'delete' => \HTTP_Request2::METHOD_DELETE, 'trace' => \HTTP_Request2::METHOD_TRACE, 'connect' => \HTTP_Request2::METHOD_CONNECT);
     $request->setMethod($methods[strtolower($method)]);
     #
     # If the current API instance has a valid token we add the Authorization
     # header with the correct token.
     #
     # In case we do not have a valid token but email and password are
     # provided we automatically use them to add a HTTP Basic Authenticaion
     # header to the request to create a new token.
     #
     if ($this->_token) {
         $headers['Authorization'] = sprintf('cc_auth_token="%s"', $this->_token);
     } else {
         if ($this->_email && $this->_password) {
             $request->setAuth($this->_email, $this->_password, \HTTP_Request2::AUTH_BASIC);
         }
     }
     #
     # The API expects the body to be urlencoded. If data was passed to
     # the request method we therefore use urlencode from urllib.
     #
     if (!empty($data)) {
         if ($request->getMethod() == \HTTP_Request2::METHOD_GET) {
             $url = $request->getUrl();
             $url->setQueryVariables($data);
         } else {
             // works with post and put
             $request->addPostParameter($data);
             $request->setBody(http_build_query($data));
         }
     }
     #
     # We set the User-Agent Header to pycclib and the local version.
     # This enables basic statistics about still used pycclib versions in
     # the wild.
     #
     $headers['User-Agent'] = sprintf('phpcclib/%s', $this->_version);
     #
     # The API expects PUT or POST data to be x-www-form-urlencoded so we
     # also set the correct Content-Type header.
     #
     if (strtoupper($method) == 'PUT' || strtoupper($method) == 'POST') {
         $headers['Content-Type'] = 'application/x-www-form-urlencoded';
     }
     #
     # We also set the Content-Length and Accept-Encoding headers.
     #
     //$headers['Content-Length'] = strlen($body);
     $headers['Accept-Encoding'] = 'compress, gzip';
     #
     # Finally we fire the actual request.
     #
     foreach ($headers as $k => $v) {
         $request->setHeader(sprintf('%s: %s', $k, $v));
     }
     for ($i = 1; $i < 6; $i++) {
         try {
             $response = $request->send();
             return $this->_return($response);
         } catch (\HTTP_Request2_Exception $e) {
             # if we could not reach the API we wait 1s and try again
             sleep(1);
             # if we tried for the fifth time we give up - and cry a little
             if ($i == 5) {
                 throw new ConnectionException('Could not connect to API...');
             }
         }
     }
 }
Exemplo n.º 15
0
 /**
  * Send an OAuth signed request with a body to the API
  *
  * @param string $url    The URL to send the request to
  * @param string $body   The raw body to PUT/POST to the URL
  * @param string $method The HTTP method to use (POST or PUT)
  *
  * @return object Instance of {@link HTTP_Request2_Response}
  * @see http://bit.ly/cdZGfr
  */
 private function _sendRequestWithBody($url, $body, $method = "PUT")
 {
     static $map = array('PUT' => HTTP_Request2::METHOD_PUT, 'POST' => HTTP_Request2::METHOD_POST);
     if (array_key_exists($method, $map)) {
         $method = $map[$method];
     } else {
         throw new Services_SimpleGeo_Exception('Invalid HTTP method ' . $method);
     }
     $signatureMethod = $this->_oauth->getSignatureMethod();
     $params = array('oauth_nonce' => (string) rand(0, 100000000), 'oauth_timestamp' => time(), 'oauth_consumer_key' => $this->_oauth->getKey(), 'oauth_signature_method' => $signatureMethod, 'oauth_version' => '1.0');
     $sig = HTTP_OAuth_Signature::factory($signatureMethod);
     $params['oauth_signature'] = $sig->build($method, $url, $params, $this->_secret);
     // Build the header
     $header = 'OAuth realm="' . $this->_api . '"';
     foreach ($params as $name => $value) {
         $header .= ", " . HTTP_OAuth::urlencode($name) . '="' . HTTP_OAuth::urlencode($value) . '"';
     }
     $req = new HTTP_Request2(new Net_URL2($url), $method);
     $req->setHeader('Authorization', $header);
     $req->setBody($body);
     try {
         $result = $req->send();
     } catch (Exception $e) {
         throw new Services_SimpleGeo_Exception($e->getMessage(), $e->getCode());
     }
     $check = (int) substr($result->getStatus(), 0, 1);
     if ($check !== 2) {
         $body = @json_decode($result->getBody());
         throw new Services_SimpleGeo_Exception($body->message, $result->getStatus());
     }
     return $result;
 }
Exemplo n.º 16
0
 public function _getResponse(S3 $s3, $url, $headers, $amz)
 {
     $req = new HTTP_Request2($url, $this->verb);
     if (!$s3->useSSLValidation) {
         $req->setConfig('ssl_verify_host', false);
         $req->setConfig('ssl_verify_peer', false);
     }
     if ($s3->proxy != null && isset($s3->proxy['host'])) {
         $req->setConfig('proxy_host');
         $req->setConfig('proxy_host', $s3->proxy['host']);
         if (isset($s3->proxy['user'], $s3->proxy['pass']) && $proxy['user'] != null && $proxy['pass'] != null) {
             $req->setConfig('proxy_user', $s3->proxy['user']);
             $req->setConfig('proxy_password', $s3->proxy['pass']);
         }
     }
     if ($s3->hasAuth()) {
         $headers = http_parse_headers(implode("\n", $headers) . $amz . "\n");
         $headers = $this->signRequest($s3, $headers);
         $req->setHeader($headers);
     }
     $req->setConfig('follow_redirects', true);
     // Request types
     switch ($this->verb) {
         case 'GET':
             break;
         case 'PUT':
         case 'POST':
             // POST only used for CloudFront
             if ($this->fp !== false) {
                 $req->setBody($this->fp);
             } elseif ($this->data !== false) {
                 $req->setBody($this->data);
             }
             break;
     }
     try {
         $res = $req->send();
         $this->response->code = $res->getStatus();
         $this->response->body = $res->getBody();
         $this->response->headers = $this->modHeaders($res->getHeader());
     } catch (HTTP_Request2_Exception $e) {
         $this->response->error = array('code' => $e->getCode(), 'message' => $e->getMessage(), 'resource' => $this->resource);
     }
     return $this->response;
 }
Exemplo n.º 17
0
function getYuduRequest($method, $url, $signature, $postData, $yuduConfig)
{
    // Create new HTTP request to send to the API.
    $request = new HTTP_Request2($url);
    $request->setConfig("ssl_verify_peer", false);
    $request->setConfig("ssl_verify_host", false);
    // Add our public authentication key as an HTTP header.
    $request->setHeader("Authentication", $yuduConfig['key']);
    // Add the signature as an HTTP header.
    $request->setHeader("Signature", $signature);
    // Set the request method, body and content type header.
    switch ($method) {
        case "GET":
            $request->setMethod(HTTP_Request2::METHOD_GET);
            break;
        case "POST":
            $request->setMethod(HTTP_Request2::METHOD_POST);
            $request->setBody($postData);
            $request->setHeader("Content-Type", "application/vnd.yudu+xml");
            break;
        case "PUT":
            $request->setMethod(HTTP_Request2::METHOD_PUT);
            $request->setBody($postData);
            $request->setHeader("Content-Type", "application/vnd.yudu+xml");
            break;
        case "DELETE":
            $request->setMethod(HTTP_Request2::METHOD_DELETE);
            $request->setBody($postData);
            $request->setHeader("Content-Type", "application/vnd.yudu+xml");
            break;
        case "OPTIONS":
            $request->setMethod(HTTP_Request2::METHOD_OPTIONS);
            break;
    }
    return $request;
}
 /**
  * Performs an HTTP PUT on the resource.
  *
  * @param string The data to upload to the (sub-) resource. May be a file
  * name or the content itself.
  * @param string The sub-resource to upload to.
  * @throws DirectedEdgeException Thrown if there is a connection problem or the resource
  * could not be found.
  */
 public function put($content, $path = "")
 {
     $request = new HTTP_Request2($this->path() . $path, HTTP_Request2::METHOD_PUT);
     $request->setBody($content, file_exists($content));
     $response = $request->send();
     if ($response->getStatus() != 200) {
         throw new DirectedEdgeException($response->getStatus(), $response->getReasonPhrase());
     }
 }
Exemplo n.º 19
0
 /**
  * Make a JSON request to the Solr server
  *
  * @param string       $body    The JSON request
  * @param integer|null $timeout If specified, the HTTP call timeout in seconds
  *
  * @return void
  */
 protected function solrRequest($body, $timeout = null)
 {
     global $configArray;
     $this->initSolrRequest($timeout);
     if ($this->backgroundUpdates) {
         if ($this->backgroundUpdates <= count($this->httpPids)) {
             $this->waitForAHttpChild();
         }
         $pid = pcntl_fork();
         if ($pid == -1) {
             throw new Exception("Could not fork background update child");
         } elseif ($pid) {
             $this->httpPids[] = $pid;
             return;
         }
     }
     $this->request->setHeader('Content-Type', 'application/json');
     $this->request->setBody($body);
     $response = null;
     $maxTries = $this->maxUpdateTries;
     for ($try = 1; $try <= $maxTries; $try++) {
         try {
             $response = $this->request->send();
         } catch (Exception $e) {
             if ($try < $maxTries) {
                 $this->log->log('solrRequest', 'Solr server request failed (' . $e->getMessage() . "), retrying in {$this->updateRetryWait} seconds...", Logger::WARNING);
                 sleep($this->updateRetryWait);
                 continue;
             }
             if ($this->backgroundUpdates) {
                 $this->log->log('solrRequest', 'Solr server request failed (' . $e->getMessage() . "). URL:\n" . $configArray['Solr']['update_url'] . "\nRequest:\n{$body}", Logger::FATAL);
                 // Kill parent and self
                 posix_kill(posix_getppid(), SIGQUIT);
                 posix_kill(getmypid(), SIGKILL);
             } else {
                 throw $e;
             }
         }
         if ($try < $maxTries) {
             $code = is_null($response) ? 999 : $response->getStatus();
             if ($code >= 300) {
                 $this->log->log('solrRequest', "Solr server request failed ({$code}), retrying in " . "{$this->updateRetryWait} seconds...", Logger::WARNING);
                 sleep($this->updateRetryWait);
                 continue;
             }
         }
         break;
     }
     $code = is_null($response) ? 999 : $response->getStatus();
     if ($code >= 300) {
         if ($this->backgroundUpdates) {
             $this->log->log('solrRequest', "Solr server request failed ({$code}). URL:\n" . $configArray['Solr']['update_url'] . "\nRequest:\n{$body}\n\nResponse:\n" . $response->getBody(), Logger::FATAL);
             // Kill parent and self
             posix_kill(posix_getppid(), SIGQUIT);
             posix_kill(getmypid(), SIGKILL);
         } else {
             throw new Exception("Solr server request failed ({$code}). URL:\n" . $configArray['Solr']['update_url'] . "\nRequest:\n{$body}\n\nResponse:\n" . $response->getBody());
         }
     }
     if ($this->backgroundUpdates) {
         // Don't let PHP cleanup e.g. the Mongo connection
         posix_kill(getmypid(), SIGKILL);
     }
 }
Exemplo n.º 20
0
<?php

require 'HTTP/Request2.php';
$url = 'http://www.example.com/meals/123';
// The request body, in JSON
$body = '[{
    "type": "appetizer",
    "dish": "Chicken Soup"
}, {
    "type": "main course",
    "dish": "Fried Monkey Brains"
}]';
$r = new HTTP_Request2($url);
$r->setMethod(HTTP_Request2::METHOD_PUT);
$r->setHeader('Content-Type', 'application/json');
$r->setBody($body);
$page = $r->send()->getBody();
Exemplo n.º 21
0
 public function checkCustomer($name)
 {
     $requestConfig = array('adapter' => 'HTTP_Request2_Adapter_Curl', 'connect_timeout' => 20, 'protocol_version' => '1.1', 'ssl_verify_peer' => false, 'ssl_verify_host' => false, 'ssl_cafile' => null, 'ssl_capath' => null, 'ssl_passphrase' => null);
     $request = new HTTP_Request2('http://testssl.alfabank.ru/CS/EQ/WSCustomerAlfaClick/WSCustomerAlfaClick10', HTTP_Request2::METHOD_POST);
     $request->setConfig($requestConfig);
     $request->setHeader('Content-Type', 'text/xml; charset=utf-8');
     $request->setHeader('SoapAction', 'WSCustomerAlfaClick#Check');
     // /CS/EQ/WSCustomerAlfaClick10#Get
     /*$request->setBody('
     <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsc="http://WSCustomerAlfaClick10.EQ.CS.ws.alfabank.ru">
        <soapenv:Header/>
        <soapenv:Body>
           <wsc:WSCustomerAlfaClickCheck>
              <inCommonParms>
                 <externalSystemCode>GRCHK14</externalSystemCode>
                 <externalUserCode>GRCHK14</externalUserCode>
                 <inCommonParmsExt>
                    <name/>
                    <value/>
                 </inCommonParmsExt>
              </inCommonParms>
              <inParms>
              <ID_client>2694835</ID_client></inParms>
           </wsc:WSCustomerAlfaClickCheck>
        </soapenv:Body>
     </soapenv:Envelope>            
             ');*/
     $request->setBody('
         <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://WSCustomerAlfaClick10.EQ.CS.ws.alfabank.ru">
         <SOAP-ENV:Body><ns1:WSCustomerAlfaClickCheck>
                  <inCommonParms>
         <externalSystemCode>GRCHK14</externalSystemCode>
         <externalUserCode>GRCHK14</externalUserCode>
      </inCommonParms>
         <inParms><ID_client>2694834</ID_client></inParms></ns1:WSCustomerAlfaClickCheck>
         </SOAP-ENV:Body></SOAP-ENV:Envelope>');
     $result = $request->send();
     echo "<pre>";
     print_r($result);
     echo "</pre>";
     return;
 }
Exemplo n.º 22
0
 /**
  * Perform an interaction of a URL.
  *
  * @param   string  $url        A URL.
  * @param   string  $pxhost     The host name of a proxy.
  *                              If it is `null', it is not used.
  * @param   int     $pxport     The port number of the proxy.
  * @param   int     $outsec     Timeout in seconds.
  *                              If it is negative, it is not used.
  * @param   array   $reqheads   An array of extension headers.
  *                              If it is `null', it is not used.
  * @param   string  $reqbody    The pointer of the entitiy body of request.
  *                              If it is `null', "GET" method is used.
  * @param   object  $res    EstraierPure_Response
  *                          an object into which headers and
  *                          the entity body of response are stored.
  *                          If it is `null', it is not used.
  * @return  int     The status code of the response.
  *                  On error, returns PEAR_Error.
  * @access  public
  * @static
  * @uses    PEAR
  * @uses    HTTP_Request2
  */
 static function shuttle_url($url, $pxhost = null, $pxport = null, $outsec = -1, $reqheads = null, $reqbody = null, $res = null)
 {
     // HTTPS checking disabled.
     /*$https = preg_match('!^https://!i', $url);
       if ($https && !extension_loaded('openssl')) {
           $err = PEAR::raiseError('HTTPS is not supported.');
           self::push_error($err);
           return $err;
       }*/
     if (is_null($reqheads)) {
         $reqheads = array();
     }
     $reqheads['User-Agent'] = sprintf('EstraierPure/%s (for PHP 5.1)', ESTRAIERPURE_VERSION);
     if (ESTRAIERPURE_USE_HTTP_STREAM) {
         // {{{ using stream functions
         // set request parameters
         $params = array('http' => array());
         if (is_null($reqbody)) {
             $params['http']['method'] = 'GET';
         } else {
             $params['http']['method'] = 'POST';
             $params['http']['content'] = $reqbody;
             $reqheads['Content-Length'] = strlen($reqbody);
         }
         if (!is_null($pxhost)) {
             /*if ($https && version_compare(phpversion(), '5.1.0', 'lt')) {
                   $err = PEAR::raiseError('HTTPS proxies are not supported.');
                   self::push_error($err);
                   return $err;
               }*/
             $params['http']['proxy'] = sprintf('tcp://%s:%d', $pxhost, $pxport);
         }
         $params['http']['header'] = '';
         foreach ($reqheads as $key => $value) {
             $params['http']['header'] .= sprintf("%s: %s\r\n", $key, $value);
         }
         $context = stream_context_create($params);
         // open a stream and send the request
         $fp = fopen($url, 'r', false, $context);
         if (!$fp) {
             $err = PEAR::raiseError(sprintf('Cannot connect to %s.', $url));
             self::push_error($err);
             return $err;
         }
         if ($outsec >= 0) {
             stream_set_timeout($fp, $outsec);
         }
         // process the response
         $meta_data = stream_get_meta_data($fp);
         if (strcasecmp($meta_data['wrapper_type'], 'cURL') == 0) {
             $errmsg = 'EstraierPure does not work with the cURL' . ' HTTP stream wrappers, please use PEAR::HTTP_Request2.';
             $err = PEAR::raiseError($errmsg);
             self::push_error($err);
             return $err;
         }
         if (!empty($meta_data['timed_out'])) {
             $err = PEAR::raiseError('Connection timed out.');
             self::push_error($err);
             return $err;
         }
         $first_header = array_shift($meta_data['wrapper_data']);
         if (!preg_match('!^HTTP/(.+?) (\\d+) ?(.*)!', $first_header, $matches)) {
             $err = PEAR::raiseError('Malformed response.');
             self::push_error($err);
             return $err;
         }
         $code = intval($matches[2]);
         if ($res instanceof EstraierPure_Response) {
             if ($res->save_heads) {
                 foreach ($meta_data['wrapper_data'] as $header) {
                     list($name, $value) = explode(':', $header, 2);
                     $res->add_head(strtolower($name), ltrim($value));
                 }
             }
             if ($res->save_body) {
                 $res->set_body(stream_get_contents($fp));
             }
         }
         // close the stream
         fclose($fp);
         // }}}
     } else {
         // {{{{ using PEAR::HTTP_Request2
         // set request parameters
         $params = array();
         $params['requestHeaders'] = $reqheads;
         if (isset($params['requestHeaders']['Content-Type'])) {
             unset($params['requestHeaders']['Content-Type']);
             $params['requestHeaders']['content-type'] = $reqheads['Content-Type'];
         }
         if (!is_null($pxhost)) {
             $params['proxy_host'] = $pxhost;
             $params['proxy_port'] = $pxport;
         }
         if ($outsec >= 0) {
             $params['timeout'] = floatval($outsec);
             $params['readTimeout'] = array($outsec, 0);
         }
         // create an instance of HTTP_Request2
         $req = new HTTP_Request2($url, $params);
         if (is_null($reqbody)) {
             $req->setMethod('GET');
         } else {
             $req->setMethod('POST');
             $req->setBody($reqbody);
         }
         // send the request
         $err = $req->sendRequest(is_object($res) && !empty($res->save_body));
         if (PEAR::isError($err)) {
             self::push_error($err);
             return $err;
         }
         $code = $req->getResponseCode();
         // process the response
         if ($res instanceof EstraierPure_Response) {
             if ($res->save_heads) {
                 $res->set_heads($req->getResponseHeader());
             }
             if ($res->save_body) {
                 $res->set_body($req->getResponseBody());
             }
         }
         // }}}
     }
     return $code;
 }
Exemplo n.º 23
0
 function simpleHttpRequest($url, $params, $method)
 {
     $req = new HTTP_Request2($url, $method, array('ssl_verify_peer' => false, 'ssl_verify_host' => false));
     //authorize
     $req->setAuth($this->user, $this->pass);
     if ($params) {
         //serialize the data
         $json = json_encode($params);
         $json ? $req->setBody($json) : false;
     }
     //set the headers
     $req->setHeader("Accept", "application/json");
     $req->setHeader("Content-Type", "application/json");
     $response = $req->send();
     if (PEAR::isError($response)) {
         return $response->getMessage();
     } else {
         return $response->getBody();
     }
 }
Exemplo n.º 24
0
 public function patch($url, $data, $headers = array())
 {
     $req = new HTTP_Request2($url);
     $req->setMethod("PATCH");
     $req->setHeader($headers);
     //$req->setConfig('ssl_verify_peer', false);
     $req->setBody($data);
     $response = $req->send();
     return $response;
 }
Exemplo n.º 25
0
 /**
  * Sets the the namespace for the specified prefix
  *
  * @param	string	$prefix			Data in the supplied format
  * @param	string	$namespace		The context the query should be run against
  */
 public function setNS($prefix, $namespace)
 {
     $this->checkRepository();
     if (empty($prefix) || empty($namespace)) {
         throw new Exception('Please supply both a prefix and a namesapce.');
     }
     $request = new HTTP_Request2($this->dsn . '/repositories/' . $this->repository . '/namespaces/' . $prefix, HTTP_Request2::METHOD_PUT);
     $request->setHeader('Content-type: text/plain');
     $request->setBody($namespace);
     $response = $request->send();
     if ($response->getStatus() != 204) {
         throw new Exception('Failed to set the namespace, HTTP response error: ' . $response->getStatus());
     }
 }
Exemplo n.º 26
0
 /**
  * Posts the xml to the suggested url using HTTP_Request2.
  */
 function do_post($xml, $optimize = false)
 {
     $url = "http://" . $GLOBALS['midcom_config']['indexer_xmltcp_host'] . ":" . $GLOBALS['midcom_config']['indexer_xmltcp_port'] . "/solr/update";
     $this->request = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
     $this->request->setBody($xml);
     $this->request->setHeader('Accept-Charset', 'UTF-8');
     $this->request->setHeader('Content-type', 'text/xml; charset=utf-8');
     if (!$this->_send_request()) {
         return false;
     }
     if ($optimize) {
         $this->request->setBody('<optimize/>');
     } else {
         $this->request->setBody('<commit/>');
     }
     if (!$this->_send_request()) {
         return false;
     }
     if ($optimize) {
         $this->request->setBody('<optimize/>');
         if (!$this->_send_request()) {
             return false;
         }
     }
     debug_add('POST ok');
     return true;
 }
Exemplo n.º 27
0
 public function testSetMultipartBody()
 {
     require_once 'HTTP/Request2/MultipartBody.php';
     $req = new HTTP_Request2('http://www.example.com/', HTTP_Request2::METHOD_POST);
     $body = new HTTP_Request2_MultipartBody(array('foo' => 'bar'), array());
     $req->setBody($body);
     $this->assertSame($body, $req->getBody());
 }
 /**
  * Send the request to Airbrake using PEAR
  * @return integer
  * @author Rich Cavanaugh
  **/
 public function pearRequest($url, $headers, $body)
 {
     if (!class_exists('HTTP_Request2')) {
         require_once 'HTTP/Request2.php';
     }
     if (!class_exists('HTTP_Request2_Adapter_Socket')) {
         require_once 'HTTP/Request2/Adapter/Socket.php';
     }
     $adapter = new HTTP_Request2_Adapter_Socket();
     $req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
     $req->setAdapter($adapter);
     $req->setHeader($headers);
     $req->setBody($body);
     return $req->send()->getStatus();
 }
Exemplo n.º 29
0
function serendipity_request_url($uri, $method = 'GET', $contenttype = null, $data = null, $extra_options = null, $addData = null, $auth = null)
{
    global $serendipity;
    require_once S9Y_PEAR_PATH . 'HTTP/Request2.php';
    $options = array('follow_redirects' => true, 'max_redirects' => 5);
    if (is_array($extra_options)) {
        foreach ($extra_options as $okey => $oval) {
            $options[$okey] = $oval;
        }
    }
    serendipity_plugin_api::hook_event('backend_http_request', $options, $addData);
    serendipity_request_start();
    if (version_compare(PHP_VERSION, '5.6.0', '<')) {
        // On earlier PHP versions, the certificate validation fails. We deactivate it on them to restore the functionality we had with HTTP/Request1
        $options['ssl_verify_peer'] = false;
    }
    switch (strtoupper($method)) {
        case 'GET':
            $http_method = HTTP_Request2::METHOD_GET;
            break;
        case 'PUT':
            $http_method = HTTP_Request2::METHOD_PUT;
            break;
        case 'OPTIONS':
            $http_method = HTTP_Request2::METHOD_OPTIONS;
            break;
        case 'HEAD':
            $http_method = HTTP_Request2::METHOD_HEAD;
            break;
        case 'DELETE':
            $http_method = HTTP_Request2::METHOD_DELETE;
            break;
        case 'TRACE':
            $http_method = HTTP_Request2::METHOD_TRACE;
            break;
        case 'CONNECT':
            $http_method = HTTP_Request2::METHOD_CONNECT;
            break;
        default:
        case 'POST':
            $http_method = HTTP_Request2::METHOD_POST;
            break;
    }
    $req = new HTTP_Request2($uri, $http_method, $options);
    if (isset($contenttype) && $contenttype !== null) {
        $req->setHeader('Content-Type', $contenttype);
    }
    if (is_array($auth)) {
        $req->setAuth($auth['user'], $auth['pass']);
    }
    if ($data != null) {
        if (is_array($data)) {
            $req->addPostParameter($data);
        } else {
            $req->setBody($data);
        }
    }
    try {
        $res = $req->send();
    } catch (HTTP_Request2_Exception $e) {
        serendipity_request_end();
        return false;
    }
    $fContent = $res->getBody();
    $serendipity['last_http_request'] = array('responseCode' => $res->getStatus(), 'effectiveUrl' => $res->getEffectiveUrl(), 'reasonPhrase' => $res->getReasonPhrase(), 'isRedirect' => $res->isRedirect(), 'cookies' => $res->getCookies(), 'version' => $res->getVersion(), 'header' => $res->getHeader(), 'object' => $res);
    serendipity_request_end();
    return $fContent;
}
Exemplo n.º 30
0
/**
 * Send a track/pingback ping
 *
 * @access public
 * @param   string  The URL to send a trackback to
 * @param   string  The XML data with the trackback contents
 * @return  string  Reponse
 */
function _serendipity_send($loc, $data, $contenttype = null)
{
    global $serendipity;
    $target = parse_url($loc);
    if ($target['query'] != '') {
        $target['query'] = '?' . str_replace('&amp;', '&', $target['query']);
    }
    if ($target['scheme'] == 'https' && empty($target['port'])) {
        $uri = $target['scheme'] . '://' . $target['host'] . $target['path'] . $target['query'];
    } elseif (!is_numeric($target['port'])) {
        $target['port'] = 80;
        $uri = $target['scheme'] . '://' . $target['host'] . ':' . $target['port'] . $target['path'] . $target['query'];
    }
    require_once S9Y_PEAR_PATH . 'HTTP/Request2.php';
    $options = array('follow_redirects' => true, 'max_redirects' => 5);
    serendipity_plugin_api::hook_event('backend_http_request', $options, 'trackback_send');
    serendipity_request_start();
    if (version_compare(PHP_VERSION, '5.6.0', '<')) {
        // On earlier PHP versions, the certificate validation fails. We deactivate it on them to restore the functionality we had with HTTP/Request1
        $options['ssl_verify_peer'] = false;
    }
    $req = new HTTP_Request2($uri, HTTP_Request2::METHOD_POST, $options);
    if (isset($contenttype)) {
        $req->setHeader('Content-Type', $contenttype);
    }
    $req->setBody($data);
    try {
        $res = $req->send();
    } catch (HTTP_Request2_Exception $e) {
        serendipity_request_end();
        return false;
    }
    $fContent = $res->getBody();
    serendipity_request_end();
    return $fContent;
}