/** * Sets the common headers required by CloudFront API * @param HTTP_Request2 $req */ private function setRequestHeaders(HTTP_Request2 $req) { $date = gmdate("D, d M Y G:i:s T"); $req->setHeader("Host", 'cloudfront.amazonaws.com'); $req->setHeader("Date", $date); $req->setHeader("Authorization", $this->generateAuthKey($date)); $req->setHeader("Content-Type", "text/xml"); }
private function request($method, $path, $params = array()) { $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)); $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); }
function getRss($url, $port, $timeout) { $results = array('rss' => array(), 'error' => ""); try { $request = new HTTP_Request2($url, HTTP_Request2::METHOD_POST); $request->setConfig("connect_timeout", $timeout); $request->setConfig("timeout", $timeout); $request->setHeader("user-agent", $_SERVER['HTTP_USER_AGENT']); $response = $request->send(); if ($response->getStatus() == 200) { // パース $body = $response->getBody(); if (substr($body, 0, 5) == "<?xml") { $results['rss'] = new MagpieRSS($body, "UTF-8"); } else { throw new Exception("Not xml data"); } } else { throw new Exception("Server returned status: " . $response->getStatus()); } } catch (HTTP_Request2_Exception $e) { $results['error'] = $e->getMessage(); } catch (Exception $e) { $results['error'] = $e->getMessage(); } // タイムアウト戻し ini_set('default_socket_timeout', $oldtimeout); return $results; }
/** * Processes the reuqest through HTTP pipeline with passed $filters, * sends HTTP request to the wire and process the response in the HTTP pipeline. * * @param array $filters HTTP filters which will be applied to the request before * send and then applied to the response. * @param IUrl $url Request url. * * @throws WindowsAzure\Common\ServiceException * * @return string The response body */ public function send($filters, $url = null) { if (isset($url)) { $this->setUrl($url); $this->_request->setUrl($this->_requestUrl->getUrl()); } $contentLength = Resources::EMPTY_STRING; if (strtoupper($this->getMethod()) != Resources::HTTP_GET && strtoupper($this->getMethod()) != Resources::HTTP_DELETE && strtoupper($this->getMethod()) != Resources::HTTP_HEAD) { $contentLength = 0; if (!is_null($this->getBody())) { $contentLength = strlen($this->getBody()); } $this->_request->setHeader(Resources::CONTENT_LENGTH, $contentLength); } foreach ($filters as $filter) { $this->_request = $filter->handleRequest($this)->_request; } $this->_response = $this->_request->send(); $start = count($filters) - 1; for ($index = $start; $index >= 0; --$index) { $this->_response = $filters[$index]->handleResponse($this, $this->_response); } self::throwIfError($this->_response->getStatus(), $this->_response->getReasonPhrase(), $this->_response->getBody(), $this->_expectedStatusCodes); return $this->_response->getBody(); }
/** * Sends a request and returns a response * * @param CartRecover_Request $request * @return Cart_Recover_Response */ public function sendRequest(CartRecover_Request $request) { $this->client->setUrl($request->getUri()); $this->client->getUrl()->setQueryVariables($request->getParams()); $this->client->setMethod($request->getMethod()); $this->client->setHeader('Accept', 'application/json'); $this->response = $this->client->send(); if ($this->response->getHeader('Content-Type') != 'application/json') { throw new CartRecover_Exception_UnexpectedValueException("Unknown response format."); } $body = json_decode($this->response->getBody(), true); $response = new CartRecover_Response(); $response->setRawResponse($this->response->getBody()); $response->setBody($body); $response->setHeaders($this->response->getHeader()); $response->setStatus($this->response->getReasonPhrase(), $this->response->getStatus()); return $response; }
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); }
/** * Send an HTTP HEAD request for the given URL * * @param string $url URL to request * @param string $errorMessage error message, if any (on return) * @return int HTTP response code or 777 on error */ function doHeadRequest($url, &$errorMessage) { $req = new HTTP_Request2($url, HTTP_Request2::METHOD_HEAD); $req->setHeader('User-Agent', 'Geeklog/' . VERSION); try { $response = $req->send(); return $response->getStatus(); } catch (HTTP_Request2_Exception $e) { $errorMessage = $e->getMessage(); return 777; } }
function getContents($url, $start = 0, $userAgent = null) { if ($start > 0) { $url .= "&start={$start}"; } $http = new HTTP_Request2($url); $http->setAdapter('curl'); if ($userAgent !== null) { $http->setHeader('User-Agent', $userAgent); } return $http->send(); }
/** * リソースリクエスト実行 * * リモートURLにアクセスしてRSSだったら配列に、 * そうでなかったらHTTP Body文字列をリソースとして扱います。 * * @return BEAR_Ro * @throws BEAR_Resource_Execute_Exception */ public function request() { $reqMethod = array(); $reqMethod[BEAR_Resource::METHOD_CREATE] = HTTP_Request2::METHOD_POST; $reqMethod[BEAR_Resource::METHOD_READ] = HTTP_Request2::METHOD_GET; $reqMethod[BEAR_Resource::METHOD_UPDATE] = HTTP_Request2::METHOD_PUT; $reqMethod[BEAR_Resource::METHOD_DELETE] = HTTP_Request2::METHOD_DELETE; assert(isset($reqMethod[$this->_config['method']])); try { // 引数以降省略可能 config で proxy とかも設定可能 $request = new HTTP_Request2($this->_config['uri'], $reqMethod[$this->_config['method']]); $request->setHeader("user-agent", 'BEAR/' . BEAR::VERSION); $request->setConfig("follow_redirects", true); if ($this->_config['method'] === BEAR_Resource::METHOD_CREATE || $this->_config['method'] === BEAR_Resource::METHOD_UPDATE) { foreach ($this->_config['values'] as $key => $value) { $request->addPostParameter($key, $value); } } $response = $request->send(); $code = $response->getStatus(); $headers = $response->getHeader(); if ($code == 200) { $body = $response->getBody(); } else { $info = array('code' => $code, 'headers' => $headers); throw $this->_exception($response->getBody(), $info); } } catch (HTTP_Request2_Exception $e) { throw $this->_exception($e->getMessage()); } catch (Exception $e) { throw $this->_exception($e->getMessage()); } $rss = new XML_RSS($body, 'utf-8', 'utf-8'); PEAR::setErrorHandling(PEAR_ERROR_RETURN); // @todo Panda::setPearErrorHandling(仮称)に変更しエラーを画面化しないようにする $rss->parse(); $items = $rss->getItems(); if (is_array($items) && count($items) > 0) { $body = $items; $headers = $rss->getChannelInfo(); $headers['type'] = 'rss'; } else { $headers['type'] = 'string'; $body = array($body); } // UTF-8に $encode = mb_convert_variables('UTF-8', 'auto', $body); $ro = BEAR::factory('BEAR_Ro')->setBody($body)->setHeaders($headers); /* @var $ro BEAR_Ro */ PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('Panda', 'onPearError')); return $ro; }
/** * 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; }
function get_data($prefix) { $url = $this->config->get_param($prefix . 'dezie_url'); $body = ""; $req = new HTTP_Request2($url); $req->setHeader('allowRedirects-Alive', true); // リダイレクトの許可設定(true/false) $req->setHeader('maxRedirects', 3); // リダイレクトの最大回数 $response = $req->send(); if ($response->getStatus() == 200) { $body = $response->getBody(); } // 通信エラー、権限設定の変更などがあるとエラー画面が表示される。 if (preg_match('/^<!DOCTYPE html>/', $body)) { throw new Exception("デヂエからのデータ取得に失敗しました。"); } // デヂエからのデータに Cookie のデータが入ってしまうので削除 $body = $this->remove_cookie($body); // デヂエから取得したレコードの中に改行が含まれている。 // レコード中の改行は LF で行末は CR+LF なので前者だけ<br>に置換する。 $body = $this->lf2br($body); return $body; }
/** * A helper function that retrieves external metadata and caches it * * @param string $url URL to fetch * @param string $id ID of the entity to fetch * @param string[] $headers Optional headers to add to the request * * @return string Metadata (typically XML) * @throws Exception */ protected function getExternalData($url, $id, $headers = []) { $cached = $this->db->uriCache->findOne(['_id' => $id, 'timestamp' => ['$gt' => new MongoDate(time() - $this->maxCacheAge)]]); if ($cached) { return $cached['data']; } if (is_null($this->request)) { $this->request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET, ['ssl_verify_peer' => false, 'follow_redirects' => true]); $this->request->setHeader('Connection', 'Keep-Alive'); $this->request->setHeader('User-Agent', 'RecordManager'); } else { $this->request->setUrl($url); } if ($headers) { $this->request->setHeader($headers); } $response = null; for ($try = 1; $try <= $this->maxTries; $try++) { try { $response = $this->request->send(); } catch (Exception $e) { if ($try < $this->maxTries) { $this->log->log('getExternalData', "HTTP request for '{$url}' failed (" . $e->getMessage() . "), retrying in {$this->retryWait} seconds...", Logger::WARNING); sleep($this->retryWait); continue; } throw $e; } if ($try < $this->maxTries) { $code = $response->getStatus(); if ($code >= 300 && $code != 404) { $this->log->log('getExternalData', "HTTP request for '{$url}' failed ({$code}), retrying " . "in {$this->retryWait} seconds...", Logger::WARNING); sleep($this->retryWait); continue; } } break; } $code = is_null($response) ? 999 : $response->getStatus(); if ($code >= 300 && $code != 404) { throw new Exception("Enrichment failed to fetch '{$url}': {$code}"); } $data = $code != 404 ? $response->getBody() : ''; $this->db->uriCache->save(['_id' => $id, 'timestamp' => new MongoDate(), 'data' => $data]); return $data; }
public static function callback() { global $HTTP_CONFIG; //exchange the code you get for a access_token $code = $_GET['code']; $request = new HTTP_Request2(self::ACCESS_TOKEN_URL); $request->setMethod(HTTP_Request2::METHOD_POST); $request->setConfig($HTTP_CONFIG); $request->addPostParameter(['client_id' => GITHUB_APP_ID, 'client_secret' => GITHUB_APP_SECRET, 'code' => $code]); $request->setHeader('Accept', 'application/json'); $response = $request->send(); $response = json_decode($response->getBody()); $access_token = $response->access_token; //Use this access token to get user details $request = new HTTP_Request2(self::USER_URL . '?access_token=' . $access_token, HTTP_Request2::METHOD_GET, $HTTP_CONFIG); $response = $request->send()->getBody(); $userid = json_decode($response)->login; //get the userid //If such a user already exists in the database //Just log him in and don't touch the access_token $already_present_token = Token::get('github', $userid); if ($already_present_token) { $_SESSION['userid'] = $userid; redirect_to('/'); } if (defined('GITHUB_ORGANIZATION')) { // perform the organization check $request = new HTTP_Request2(json_decode($response)->organizations_url . '?access_token=' . $access_token, HTTP_Request2::METHOD_GET, $HTTP_CONFIG); $response = $request->send()->getBody(); //List of organizations $organizations_list = array_map(function ($repo) { return $repo->login; }, json_decode($response)); if (in_array(GITHUB_ORGANIZATION, $organizations_list)) { $_SESSION['userid'] = $userid; Token::add('github', $userid, $access_token); } else { throw new Exception('You are not in the listed members.'); } } else { $_SESSION['userid'] = $userid; Token::add('github', $userid, $access_token); } redirect_to('/'); }
/** * 記事を投稿する. * * @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; }
/** * Send a POST request to the specified URL with the specified payload. * @param string $url * @param string $data * @return string Remote data **/ public function sendPOST($url, $data = array()) { $data['_fake_status'] = '200'; // Send the actual request. $this->instance->setHeader('User-Agent', sprintf(Imgur::$user_agent, Imgur::$key)); $this->instance->setMethod('POST'); $this->instance->setUrl($url); foreach ($data as $k => $v) { $this->instance->addPostParameter($k, $v); } try { /** @var HTTP_Request2_Response */ $response = $this->instance->send(); return $response->getBody(); } catch (HTTP_Request2_Exception $e) { throw new Imgur_Exception("HTTP Request Failure", null, $e); } catch (Exception $e) { throw new Imgur_Exception("Unknown Failure during HTTP Request", null, $e); } }
public static function Post_Uri_Params($request_uri, $headers, $params, array $postFiles = null) { $request = new HTTP_Request2($request_uri, HTTP_Request2::METHOD_POST); $request->setHeader($headers)->addPostParameter($params); if (count($postFiles)) { foreach ($postFiles as $key => $value) { $request->addUpload($key, $value['tmp_name'], $value['name']); } } try { $response = $request->send(); if (200 == $response->getStatus()) { return $response->getBody(); } else { return false; } } catch (HTTP_Request2_Exception $e) { return false; } }
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(); } }
/** * Loads the XRD file from the given URL. * Sets $react->error when loading fails * * @param string $url URL to fetch * * @return boolean True if loading data succeeded, false if not */ protected function loadXrd($url) { try { $react = new Net_WebFinger_Reaction(); $react->url = $url; $react->error = null; if ($this->httpClient !== null) { $this->httpClient->setUrl($url); $this->httpClient->setHeader('user-agent', 'PEAR Net_WebFinger', true); $this->httpClient->setHeader('accept', 'application/jrd+json, application/xrd+xml;q=0.9', true); $res = $this->httpClient->send(); $code = $res->getStatus(); if (intval($code / 100) !== 2) { throw new Net_WebFinger_Error('Error loading XRD file: ' . $res->getStatus() . ' ' . $res->getReasonPhrase(), Net_WebFinger_Error::NOT_FOUND); } $react->loadString($res->getBody()); } else { $context = stream_context_create(array('http' => array('user-agent' => 'PEAR Net_WebFinger', 'header' => 'accept: application/jrd+json, application/xrd+xml;q=0.9', 'follow_location' => true, 'max_redirects' => 20))); $content = @file_get_contents($url, false, $context); if ($content === false) { $msg = 'Error loading XRD file'; if (isset($http_response_header)) { $status = null; //we need this because there will be several HTTP/.. // status lines when redirection is going on. foreach ($http_response_header as $header) { if (substr($header, 0, 5) == 'HTTP/') { $status = $header; } } $msg .= ': ' . $status; } throw new Net_WebFinger_Error($msg, Net_WebFinger_Error::NOT_FOUND, new Net_WebFinger_Error('file_get_contents on ' . $url)); } $react->loadString($content); } } catch (Exception $e) { $react->error = $e; } return $react; }
/** * Get the Pingback URL for a given URL * * @param string $url URL to get the Pingback URL for * @return string Pingback URL or empty string */ function PNB_getPingbackUrl($url) { $req = new HTTP_Request2($url, HTTP_Request2::METHOD_HEAD); $req->setHeader('User-Agent', 'Geeklog/' . VERSION); try { $response = $req->send(); $retval = $response->getHeader('x-pingback'); } catch (HTTP_Request2_Exception $e) { COM_errorLog('Pingback (HEAD): ' . $e->getMessage()); return false; } if (empty($retval)) { // search for <link rel="pingback"> $req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET); $req->setHeader('User-Agent', 'Geeklog/' . VERSION); try { $response = $req->send(); $status = $response->getStatus(); if ($status == 200) { $body = $response->getBody(); // only search for the first match - it doesn't make sense to have // more than one pingback URL $found = preg_match("/<link rel=\"pingback\"[^>]*href=[\"']([^\"']*)[\"'][^>]*>/i", $body, $matches); if ($found === 1 && !empty($matches[1])) { $url = str_replace('&', '&', $matches[1]); $retval = urldecode($url); } } else { COM_errorLog("Pingback (GET): Got HTTP response code {$status} when requesting {$url}"); return false; } } catch (HTTP_Request2_Exception $e) { COM_errorLog('Pingback (GET): ' . $e->getMessage()); return false; } } return $retval; }
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); }
/** * Handle a pingback for an entry. * Also takes care of the speedlimit and spam. Assumes that the caller of this * function has already checked permissions! * * @param string $id ID of entry that got pinged * @param string $type type of that entry ('article' for stories, etc.) * @param string $url URL of the page that pinged us * @param string $oururl URL that got pinged on our site * @return object XML-RPC response */ function PNB_handlePingback($id, $type, $url, $oururl) { global $_CONF, $_TABLES, $PNB_ERROR; require_once 'HTTP/Request.php'; if (!isset($_CONF['check_trackback_link'])) { $_CONF['check_trackback_link'] = 2; } // handle pingbacks to articles on our own site $skip_speedlimit = false; if ($_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR']) { if (!isset($_CONF['pingback_self'])) { $_CONF['pingback_self'] = 0; // default: skip self-pingbacks } if ($_CONF['pingback_self'] == 0) { return new XML_RPC_Response(new XML_RPC_Value($PNB_ERROR['skipped'])); } elseif ($_CONF['pingback_self'] == 2) { $skip_speedlimit = true; } } COM_clearSpeedlimit($_CONF['commentspeedlimit'], 'pingback'); if (!$skip_speedlimit) { $last = COM_checkSpeedlimit('pingback'); if ($last > 0) { return new XML_RPC_Response(0, 49, sprintf($PNB_ERROR['speedlimit'], $last, $_CONF['commentspeedlimit'])); } } // update speed limit in any case COM_updateSpeedlimit('pingback'); if ($_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR']) { if ($_CONF['check_trackback_link'] & 4) { $parts = parse_url($url); if (empty($parts['host'])) { TRB_logRejected('Pingback: No valid URL', $url); return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']); } else { $ip = gethostbyname($parts['host']); if ($ip != $_SERVER['REMOTE_ADDR']) { TRB_logRejected('Pingback: IP address mismatch', $url); return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']); } } } } // See if we can read the page linking to us and extract at least // the page's title out of it ... $title = ''; $excerpt = ''; $req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET); $req->setHeader('User-Agent', 'Geeklog/' . VERSION); try { $response = $req->send(); $status = $response->getStatus(); if ($status == 200) { $body = $response->getBody(); if ($_CONF['check_trackback_link'] & 3) { if (!TRB_containsBacklink($body, $oururl)) { TRB_logRejected('Pingback: No link to us', $url); $comment = TRB_formatComment($url); PLG_spamAction($comment, $_CONF['spamx']); return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']); } } preg_match(':<title>(.*)</title>:i', $body, $content); if (empty($content[1])) { $title = ''; // no title found } else { $title = trim(COM_undoSpecialChars($content[1])); } if ($_CONF['pingback_excerpt']) { // Check which character set the site that sent the Pingback // is using $charset = 'ISO-8859-1'; // default, see RFC 2616, 3.7.1 $ctype = $response->getHeader('content-type'); $c = explode(';', $ctype); foreach ($c as $ct) { $ch = explode('=', trim($ct)); if (count($ch) === 2) { if (trim($ch[0]) === 'charset') { $charset = trim($ch[1]); break; } } } if (!empty($charset) && strcasecmp($charset, COM_getCharset()) !== 0) { if (function_exists('mb_convert_encoding')) { $body = @mb_convert_encoding($body, COM_getCharset(), $charset); } elseif (function_exists('iconv')) { $body = @iconv($charset, COM_getCharset(), $body); } // else: tough luck ... } $excerpt = PNB_makeExcerpt($body, $oururl); } // we could also run the rest of the other site's page // through the spam filter here ... } elseif ($_CONF['check_trackback_link'] & 3) { COM_errorLog("Pingback verification: Got HTTP response code " . $response->getStatus() . " when requesting {$url}"); return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']); } } catch (HTTP_Request2_Exception $e) { if ($_CONF['check_trackback_link'] & 3) { // we were supposed to check for backlinks but didn't get the page COM_errorLog("Pingback verification: " . $e->getMessage() . " when requesting {$url}"); return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']); } } // check for spam first $saved = TRB_checkForSpam($url, $title, '', $excerpt); if ($saved == TRB_SAVE_SPAM) { return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']); } // save as a trackback comment $saved = TRB_saveTrackbackComment($id, $type, $url, $title, '', $excerpt); if ($saved == TRB_SAVE_REJECT) { return new XML_RPC_Response(0, 49, $PNB_ERROR['multiple']); } if (isset($_CONF['notification']) && in_array('pingback', $_CONF['notification'])) { TRB_sendNotificationEmail($saved, 'pingback'); } return new XML_RPC_Response(new XML_RPC_Value($PNB_ERROR['success'])); }
$request->setConfig($Config['Request-Config']); if (!empty($Config['Login']) && !empty($Config['Password'])) { $request->setAuth($Config['Login'], $Config['Password']); } $headers = headers(); 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-In-Exclude']); foreach ($headers as $name => $value) { $request->setHeader($name, $value); } if (!empty($_POST)) { foreach ($_POST as $key => $value) { $request->addPostParameter($key, $value); } } // @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);
public function testBug15937() { $req = new HTTP_Request2(); $autoHeaders = $req->getHeaders(); $req->setHeader('Expect: '); $req->setHeader('Foo', ''); $this->assertEquals(array('expect' => '', 'foo' => '') + $autoHeaders, $req->getHeaders()); }
/** * Required to request the root i-name (XRI) XRD which will provide an * error message that the i-name does not exist, or else return a valid * XRD document containing the i-name's Canonical ID. * * @param string $url URI * @param string $serviceType Optional service type * * @return HTTP_Request * @todo Finish this a bit better using the QXRI rules. */ protected function get($url, $serviceType = null) { $request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET, $this->getHttpRequestOptions()); $netURL = new Net_URL2($url); $request->setHeader('Accept', 'application/xrds+xml'); if ($serviceType) { $netURL->setQueryVariable('_xrd_r', 'application/xrds+xml'); $netURL->setQueryVariable('_xrd_t', $serviceType); } else { $netURL->setQueryVariable('_xrd_r', 'application/xrds+xml;sep=false'); } $request->setURL($netURL->getURL()); try { return $request->send(); } catch (HTTP_Request2_Exception $e) { throw new Services_Yadis_Exception('Invalid response to Yadis protocol received: ' . $e->getMessage(), $e->getCode()); } }
/** * Call MetaLib X-Server * * @param array $params URL Parameters * * @return string XML * @throws Exception */ protected function callXServer($params) { $request = new HTTP_Request2($this->baseURL, HTTP_Request2::METHOD_GET, ['ssl_verify_peer' => false]); $request->setHeader('User-Agent', 'RecordManager'); $url = $request->getURL(); $url->setQueryVariables($params); $cleanUrl = preg_replace('/user_password=([^&]+)/', 'user_password=***', $url->getURL()); $this->_message("Sending request: {$cleanUrl}", true); $response = $request->send(); $code = $response->getStatus(); if ($code >= 300) { $this->_message("Request '{$url}' failed: {$code}", false, Logger::FATAL); throw new Exception("Request failed: {$code}"); } $this->_message("Request successful", true); return $response->getBody(); }
function fetchUrlPear($url, $request_parameters) { if (VERBOSE) { logEvent($url . ' fetching with PEAR'); } if (0 && $GLOBALS['has_pear_http_request'] == 2) { $headreq = new HTTP_Request2($url, $request_parameters); $headreq->setHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)'); } else { $headreq = new HTTP_Request($url, $request_parameters); $headreq->addHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)'); } if (!PEAR::isError($headreq->sendRequest(false))) { $code = $headreq->getResponseCode(); if ($code != 200) { logEvent('Fetching ' . $url . ' failed, error code ' . $code); return 0; } $header = $headreq->getResponseHeader(); if (preg_match('/charset=(.*)/i', $header['content-type'], $regs)) { $remote_charset = strtoupper($regs[1]); } $request_parameters['method'] = 'GET'; if (0 && $GLOBALS['has_pear_http_request'] == 2) { $req = new HTTP_Request2($url, $request_parameters); $req->setHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)'); } else { $req = new HTTP_Request($url, $request_parameters); $req->addHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)'); } logEvent('Fetching ' . $url); if (VERBOSE && function_exists('output')) { output('Fetching remote: ' . $url); } if (!PEAR::isError($req->sendRequest(true))) { $content = $req->getResponseBody(); if ($remote_charset != 'UTF-8' && function_exists('iconv')) { $content = iconv($remote_charset, 'UTF-8//TRANSLIT', $content); } } else { logEvent('Fetching ' . $url . ' failed on GET ' . $req->getResponseCode()); return 0; } } else { logEvent('Fetching ' . $url . ' failed on HEAD'); return 0; } return $content; }
/** * Constructor * * @param array $args * @access public * @return void */ public function __construct(array $args) { if (!class_exists('HTTP/Request2.php', false)) { spl_autoload_register(array(__CLASS__, 'autoload')); } $base = ''; if (isset($args['base'])) { $base = $args['base']; } else { throw new Exception("Missing argument named 'base' for rpc base url."); } $base = rtrim($base, '\\//') . '/'; $timeout = isset($args['timeout']) ? $args['timeout'] : 1; $agent = isset($args['agent']) ? $args['agent'] : __CLASS__ . '/' . self::VERSION; $adapter = isset($args['adapter']) ? $args['adapter'] : 'HTTP_Request2_Adapter_Socket'; $config = array('adapter' => $adapter, 'timeout' => $timeout); $client = new \HTTP_Request2(null, \HTTP_Request2::METHOD_POST, $config); $client->setHeader('user-agent', $agent); $this->_client = $client; $this->_base = $base; $this->_parser = new Parser(); }
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']; } }
/** * Returns the size of the repository * * @param string $context The context the query should be run against * * @return int */ public function size($context = 'null') { $this->checkRepository(); $request = new HTTP_Request2($this->dsn . '/repositories/' . $this->repository . '/size?context=' . $context, HTTP_Request2::METHOD_POST); $request->setHeader('Accept: text/plain'); $response = $request->send(); if ($response->getStatus() != 200) { throw new Exception('Failed to run query, HTTP response error: ' . $response->getStatus()); } return (int) $response->getBody(); }
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(); } }