/** * Test that the default privacy setting is used when an existing * bookmark is updated with edit.php. */ public function testDefaultPrivacyEdit() { $this->setUnittestConfig(array('defaults' => array('privacy' => 2))); list($req, $uId) = $this->getLoggedInRequest('?unittestMode=1'); $cookies = $req->getCookieJar(); $req->setMethod(HTTP_Request2::METHOD_POST); $req->addPostParameter('url', 'http://www.example.org/testdefaultprivacyposts_edit'); $req->addPostParameter('description', 'Test bookmark 2 for default privacy.'); $req->addPostParameter('status', '0'); $res = $req->send(); $this->assertEquals(200, $res->getStatus(), 'Adding bookmark failed: ' . $res->getBody()); $bms = $this->bs->getBookmarks(0, null, $uId); $bm = reset($bms['bookmarks']); $bmId = $bm['bId']; $reqUrl = $GLOBALS['unittestUrl'] . 'edit.php/' . $bmId . '?unittestMode=1'; $req2 = new HTTP_Request2($reqUrl, HTTP_Request2::METHOD_POST); $req2->setCookieJar($cookies); $req2->addPostParameter('address', 'http://www.example.org/testdefaultprivacyposts_edit'); $req2->addPostParameter('title', 'Test bookmark 2 for default privacy.'); $req2->addPostParameter('submitted', '1'); $res = $req2->send(); $this->assertEquals(302, $res->getStatus(), 'Editing bookmark failed'); $bm = $this->bs->getBookmark($bmId); $this->assertEquals('2', $bm['bStatus']); }
/** * POST Request * * @param $url * @param $datas * @return string */ public function post_request($url, $datas = array()) { $body = ''; try { $this->http->setURL($url); $this->http->setMethod(HTTP_Request2::METHOD_POST); foreach ($datas as $key => $val) { $this->http->addPostParameter($key, mb_convert_encoding($val, $this->response_encoding, 'UTF-8')); } if (!empty($this->cookies)) { foreach ($this->cookies as $cookie) { $this->http->addCookie($cookie['name'], $cookie['value']); } } $response = $this->http->send(); if (count($response->getCookies())) { $this->cookies = $response->getCookies(); } $body = mb_convert_encoding($response->getBody(), 'UTF-8', $this->response_encoding); } catch (Exception $e) { debug($e->getMessage()); } return $body; }
/** * Http request * * @param string $method * @param string $url * @param array $submit * @param string $formName * * @return HTTP_Request2_Response */ public function request($method, $url, array $submit = array(), $formName = 'form') { $this->request = new HTTP_Request2(); $url = new Net_URL2($url); $this->request->setMethod($method); if ($submit) { $submit = array_merge(array('_token' => '0dc59902014b6', '_qf__' . $formName => ''), $submit); } if ($submit && $method === 'POST') { $this->request->addPostParameter($submit); } if ($submit && $method === 'GET') { $url->setQueryVariables($submit); } $this->request->setUrl($url); $this->response = $this->request->send(); return $this; }
public function send($mobile, $content) { $data = array('u' => $this->conf['u'], 'p' => md5($this->conf['p']), 'm' => $mobile, 'c' => $content . $this->conf['sign']); $http = new HTTP_Request2($this->conf['apiUriPrefix'] . 'sms', HTTP_Request2::METHOD_POST); $http->addPostParameter($data); $r = $http->send()->getBody(); if ($r != 0) { throw new Services_Sms_Exception($r); } return true; }
public function send($mobile, $content) { $data = array('sname' => $this->conf['sname'], 'spwd' => $this->conf['spwd'], 'scorpid' => $this->conf['scorpid'], 'sprdid' => $this->conf['sprdid'], 'sdst' => $mobile, 'smsg' => $content . $this->conf['sign']); $http = new HTTP_Request2($this->conf['apiUriPrefix'] . '/g_Submit', HTTP_Request2::METHOD_POST); $http->addPostParameter($data); $r = $http->send()->getBody(); $tmp = $this->filter($r); if ($tmp['State'] != 0) { throw new Services_Sms_Exception($r); } return true; }
public function testStreaming() { $req = new HTTP_Request2(null, HTTP_Request2::METHOD_POST); $body = $req->addPostParameter('foo', 'I am a parameter')->addUpload('upload', dirname(dirname(__FILE__)) . '/_files/plaintext.txt')->getBody(); $asString = ''; while ($part = $body->read(10)) { $asString .= $part; } $this->assertEquals($body->getLength(), strlen($asString)); $this->assertContains('This is a test.', $asString); $this->assertContains('I am a parameter', $asString); }
/** * リソースリクエスト実行 * * リモート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; }
protected static function post($url, $content) { $request = new HTTP_Request2($url); $request->setMethod(HTTP_Request2::METHOD_POST); foreach ($content as $name => $val) { $request->addPostParameter($name, $val); } $request->setConfig(array('ssl_verify_peer' => false)); try { $response = $request->send(); $body = $response->getBody(); return $body; } catch (HTTP_Request2_Exception $e) { return false; } }
public function post($url, $data, $headers = array(), $auth = false) { $req = new HTTP_Request2($url); $req->setMethod(HTTP_Request2::METHOD_POST); $req->setHeader($headers); if ($auth) { $req->setAuth($auth['username'], $auth['password']); } //$req->setConfig('ssl_verify_peer', false); if (is_array($data)) { $req->addPostParameter($data); } else { $req->setBody($data); } $response = $req->send(); return $response; }
public function send($mobile, $content) { //需要国家码 if (stripos($mobile, '86') !== 0) { $mobile = '86' . $mobile; } //移通 会在短信里自动加上签名【xxx】,所以不用自己加了。 $data = array('command' => 'MT_REQUEST', 'spid' => $this->conf['spid'], 'sppassword' => $this->conf['sppassword'], 'da' => $mobile, 'dc' => '8', 'sm' => bin2hex(mb_convert_encoding($content, 'UTF-16BE', 'UTF-8'))); $http = new HTTP_Request2($this->conf['apiUriPrefix'] . 'sms/mt', HTTP_Request2::METHOD_POST); $http->addPostParameter($data); $r = $http->send()->getBody(); parse_str($r, $tmp); if ($tmp['mterrcode'] != '000') { throw new Services_Sms_Exception($r); } return true; }
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('/'); }
/** * 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 requestToPostMethod($argURL, $argParams = NULL, $argFiles = NULL, $argTimeOut = 60) { $HttpRequestObj = new HTTP_Request2(); $urls = parse_url($argURL); if (isset($urls["user"]) && isset($urls["pass"])) { $HttpRequestObj->setAuth($urls["user"], $urls["pass"]); } if (isset($urls["port"])) { $url = $urls["scheme"] . '://' . $urls["host"] . ':' . $urls["port"]; } else { $url = $urls["scheme"] . '://' . $urls["host"]; } if (isset($urls["path"])) { $url .= $urls["path"]; } $HttpRequestObj->setUrl($url); $HttpRequestObj->setMethod(HTTP_Request2::METHOD_POST); if ('https' === $urls["scheme"]) { $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut, 'adapter' => 'HTTP_Request2_Adapter_Curl', 'ssl_verify_peer' => FALSE, 'ssl_verify_host' => FALSE)); } else { $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut)); } if (is_array($argParams)) { foreach ($argParams as $key => $value) { $HttpRequestObj->addPostParameter($key, $value); } } // ファイルをアップロードする場合 if (is_array($argFiles)) { foreach ($argFiles as $key => $value) { $HttpRequestObj->addUpload($key, $value); } } // リクエストを送信 $response = $HttpRequestObj->send(); // レスポンスのボディ部を表示 return $response; }
public function delete_mailinglist($list) { $req = new HTTP_Request2($this->url . "/com/delmailinglistnow"); $req->setMethod(HTTP_Request2::METHOD_POST); $req->getUrl()->setQueryVariables($this->auth); $req->addPostParameter(array('modu' => $list)); $resp = $req->send(); // refresh lists in class $this->get_mailinglists(); }
/** * Performs a simple Query. * * Performs a query and returns the result in the selected format. Throws an * exception if the query returns an error. * * @param string $query String used for query * @param string $resultFormat Returned result format, see const definitions for supported list. * @param string $queryLang Language used for querying, SPARQL and SeRQL supported * @param bool $infer Use inference in the query * * @return phpSesame_SparqlRes */ public function query($query, $resultFormat = self::SPARQL_XML, $queryLang = 'sparql', $infer = true) { $this->checkRepository(); $this->checkQueryLang($queryLang); $this->checkResultFormat($resultFormat); $request = new HTTP_Request2($this->dsn . '/repositories/' . $this->repository, HTTP_Request2::METHOD_POST); $request->setHeader('Accept: ' . self::SPARQL_XML); $request->addPostParameter('query', $query); $request->addPostParameter('queryLn', $queryLang); $request->addPostParameter('infer', $infer); $response = $request->send(); if ($response->getStatus() != 200) { print_r('query: ' . $query); var_dump($response); throw new Exception('Failed to run query, HTTP response error: ' . $response->getStatus()); } //print_r('No error: '.$response->getStatus()); //print_r('request: '.$request->getHeaders()); //print_r($response->getBody()); return new phpSesame_SparqlRes($response->getBody()); }
/** * Sets HTTP POST parameters. * * @param array $postParameters The HTTP POST parameters. * * @return none */ public function setPostParameters($postParameters) { $this->_request->addPostParameter($postParameters); }
/** * Make a low-level web hit to this site, with authentication. * @param string $path URL fragment for something under the base path * @param array $params POST parameters to send * @param boolean $auth whether to include auth data * @return string * @throws Exception on low-level error conditions */ protected function hit($path, $params = array(), $auth = false, $cookies = array()) { $url = $this->basepath . '/' . $path; $http = new HTTP_Request2($url, 'POST'); if ($auth) { $http->setAuth($this->username, $this->password, HTTP_Request2::AUTH_BASIC); } foreach ($cookies as $name => $val) { $http->addCookie($name, $val); } $http->addPostParameter($params); $response = $http->send(); $code = $response->getStatus(); if ($code < '200' || $code >= '400') { throw new Exception("Failed API hit to {$url}: {$code}\n" . $response->getBody()); } return $response; }
/** * Performs an update Query. * * Performs an update query. Throws an * exception if the query returns an error. * * @param string $query String used for query * */ public function update($query) { $this->checkRepository(); $url = $this->dsn . '/repositories/' . $this->repository . '/statements'; $request = new HTTP_Request2($url, HTTP_Request2::METHOD_POST); $request->addPostParameter('update', $query); $request->setHeader('Content-type: ' . self::FORM . ';charset=' . $this->contentCharset); $request = $this->prepareRequest($request); $response = $request->send(); if ($response->getStatus() != 204) { throw new \Exception('Failed to run update query, HTTP response error: ' . $response->getStatus()); } }
function request($method, $url, $token, $params, $file) { $req = new HTTP_Request2($url); $req->setMethod($method == "get" ? 'GET' : 'POST'); $req->setHeader("X-Gallery-Request-Method", $method); if ($token) { $req->setHeader("X-Gallery-Request-Key", $token); } foreach ($params as $key => $value) { $req->addPostParameter($key, is_string($value) ? $value : json_encode($value)); } if ($file) { $req->addUpload("file", $file, basename($file), mime_content_type($file)); } $response = $req->send(); $status = $response->getStatus(); switch ($status) { case 200: case 201: return json_decode($response->getBody()); case 403: throw new Gallery3_Forbidden_Exception($response->getBody(), $status); default: throw new Gallery3_Exception($response->getBody(), $status); } }
$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); fclose($fp); break; } }
/** * Re-send a request after successful re-authentication * Re-creates a GET or POST request based on data passed along in a form. Used * in case of an expired security token so that the user doesn't lose changes. */ function resend_request() { global $_CONF; $method = ''; if (isset($_POST['token_requestmethod'])) { $method = COM_applyFilter($_POST['token_requestmethod']); } $returnUrl = ''; if (isset($_POST['token_returnurl'])) { $returnUrl = urldecode($_POST['token_returnurl']); if (substr($returnUrl, 0, strlen($_CONF['site_url'])) != $_CONF['site_url']) { // only accept URLs on our site $returnUrl = ''; } } $postData = ''; if (isset($_POST['token_postdata'])) { $postData = urldecode($_POST['token_postdata']); } $getData = ''; if (isset($_POST['token_getdata'])) { $getData = urldecode($_POST['token_getdata']); } $files = ''; if (isset($_POST['token_files'])) { $files = urldecode($_POST['token_files']); } if (SECINT_checkToken() && !empty($method) && !empty($returnUrl) && ($method === 'POST' && !empty($postData) || $method === 'GET' && !empty($getData))) { $magic = get_magic_quotes_gpc(); if ($method === 'POST') { $req = new HTTP_Request2($returnUrl, HTTP_Request2::METHOD_POST); $data = unserialize($postData); foreach ($data as $key => $value) { if ($key == CSRF_TOKEN) { $req->addPostParameter($key, SEC_createToken()); } else { if ($magic) { $value = stripslashes_gpc_recursive($value); } $req->addPostParameter($key, $value); } } if (!empty($files)) { $files = unserialize($files); } if (!empty($files)) { foreach ($files as $key => $value) { $req->addPostParameter('_files_' . $key, $value); } } } else { $data = unserialize($getData); foreach ($data as $key => &$value) { if ($key == CSRF_TOKEN) { $value = SEC_createToken(); } else { if ($magic) { $value = stripslashes_gpc_recursive($value); } } } $returnUrl = $returnUrl . '?' . http_build_query($data); $req = new HTTP_Request2($returnUrl, HTTP_Request2::METHOD_GET); } $req->setHeader('User-Agent', 'Geeklog/' . VERSION); // need to fake the referrer so the new token matches $req->setHeader('Referer', COM_getCurrentUrl()); foreach ($_COOKIE as $cookie => $value) { $req->addCookie($cookie, $value); } try { $response = $req->send(); $status = $response->getStatus(); if ($status == 200) { COM_output($response->getBody()); } else { throw new HTTP_Request2_Exception('HTTP error: status code = ' . $status); } } catch (HTTP_Request2_Exception $e) { if (!empty($files)) { SECINT_cleanupFiles($files); } trigger_error("Resending {$method} request failed: " . $e->getMessage()); } } else { if (!empty($files)) { SECINT_cleanupFiles($files); } COM_redirect($_CONF['site_url'] . '/index.php'); } // don't return exit; }
/** * Fetches a json response via HTTP request * @todo Support cookies (to allow login and similiar features) * @param string $url URL to get json from * @param array $data (optional) HTTP post data * @param boolean $secure (optional) Wheter to verify peer using SSL or not, default false * @param string $certificateFile (optional) Local certificate file for non public SSL certificates * @param array Set an optional HTTP Authentication method and supply its login credentials. * The supplied array must comply with the following structure: * <pre class="brush: php"> * $httpAuth = array( * 'httpAuthMethod' => 'none|basic|disgest', * 'httpAuthUsername' => '<username>', * 'httpAuthPassword' => '<password>', * ); * </pre> * @return mixed Decoded JSON on success, false otherwise */ public function getJson($url, $data = array(), $secure = false, $certificateFile = '', $httpAuth = array(), $files = array()) { $request = new \HTTP_Request2($url, \HTTP_Request2::METHOD_POST); if (!empty($httpAuth)) { switch ($httpAuth['httpAuthMethod']) { case 'basic': $request->setAuth($httpAuth['httpAuthUsername'], $httpAuth['httpAuthPassword'], \HTTP_Request2::AUTH_BASIC); break; case 'disgest': $request->setAuth($httpAuth['httpAuthUsername'], $httpAuth['httpAuthPassword'], \HTTP_Request2::AUTH_DIGEST); break; case 'none': default: break; } } foreach ($data as $name => $value) { $request->addPostParameter($name, $value); } if (!empty($files)) { foreach ($files as $fieldId => $file) { $request->addUpload($fieldId, $file); } } if ($this->sessionId !== null) { $request->addCookie(session_name(), $this->sessionId); } $request->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false, 'follow_redirects' => true, 'strict_redirects' => true)); $response = $request->send(); //echo '<pre>';var_dump($response->getBody());echo '<br /><br />'; $cookies = $response->getCookies(); foreach ($cookies as &$cookie) { if ($cookie['name'] === session_name()) { $this->sessionId = $cookie['value']; break; } } if ($response->getStatus() != 200) { \DBG::msg(__METHOD__ . ' Request failed! Status: ' . $response->getStatus()); \DBG::msg('URL: ' . $url); \DBG::dump($data); return false; } $body = json_decode($response->getBody()); if ($body === NULL) { \DBG::msg(__METHOD__ . ' failed!'); \DBG::dump($response->getBody()); } return $body; }
public function ajaxAction() { $this->view = new Lupin_View(); $method = strtolower($this->_request->getParam('method')); $query_uri = trim($this->_request->getParam('query_uri'), '/ '); $url = $this->_request->getParam('url'); $ssl = $this->_request->getParam('ssl'); $extraParams = $this->_request->getParam('param'); $params = array(); $session_query_uri = '/' . substr($query_uri, 0, strrpos($query_uri, '.')); $test_history = new Zend_Session_Namespace('test_history'); $history = $test_history->value; $history[$session_query_uri] = $this->getRequest()->getParams(); $test_history->value = $history; if (!empty($extraParams)) { foreach ($extraParams as $newParam) { $parms = explode('=', $newParam, 2); if (count($parms) > 1) { list($key, $value) = $parms; $params[$key] = $value; } } } require_once 'HTTP/Request2.php'; $newMethod = HTTP_Request2::METHOD_GET; switch ($method) { case 'get': $newMethod = HTTP_Request2::METHOD_GET; break; case 'post': $newMethod = HTTP_Request2::METHOD_POST; break; case 'put': $newMethod = HTTP_Request2::METHOD_PUT; break; case 'delete': $newMethod = HTTP_Request2::METHOD_DELETE; break; case 'head': $newMethod = HTTP_Request2::METHOD_HEAD; break; } $email = $this->_request->getParam('email'); $pass = $this->_request->getParam('secretKey'); $request_url = 'http' . ($ssl == true ? 's' : '') . '://' . $url . '/' . $query_uri; $request = new HTTP_Request2($request_url, $newMethod); if ($email && $pass) { $request->setAuth($email, $pass, HTTP_Request2::AUTH_DIGEST); $request->setHeader(array( 'Accept' => '*/*' )); } if ($method == 'post') { $request->addPostParameter($params); } else { $url = $request->getUrl(); $url->setQueryVariables(array() + $params); } try { $res = $request->send(); } catch (Exception $e) { return $this->view->renderJson(array( 'request_url' => $request_url, 'response_headers' => $this->collapseHeaders(array( 'error' => $e->getMessage()) ), 'content' => $e->getMessage(), 'status' => 'Could not connect', 'method' => strtoupper($method) )); } $response = array( 'request_url' => $request_url, 'response_headers' => $this->collapseHeaders($res->getHeader()), 'content' => $res->getBody(), 'status' => $res->getStatus(), 'method' => strtoupper($method), ); $this->view->renderJson($response); }
function postForm() { require_once 'HTTP/Request2.php'; $timestamp = date('YmdHis'); $request = new HTTP_Request2('http://www.kultunaut.dk/perl/arradd/type-nynaut/timestamp-' . $timestamp, HTTP_Request2::METHOD_POST); $summary = $this->context->getEvent()->title; $short_description = $this->context->getEvent()->summary; $long_description = $this->context->getEvent()->content; $start_date_day = $this->context->getDateStart()->format('d'); $start_date_month = $this->context->getDateStart()->format('n'); $start_date_year = $this->context->getDateStart()->format('Y'); $end_date_day = $this->context->getDateEnd()->format('d'); $end_date_month = $this->context->getDateEnd()->format('n'); $start_date_year = $this->context->getDateEnd()->format('Y'); if ($this->context->getDateStart()->format('i') == '00') { $time = 'kl. ' . $this->context->getDateStart()->format('H'); } else { $time = 'kl. ' . $this->context->getDateStart()->format('H') . '.' . $this->context->getDateStart()->format('i'); } $genre = 'Foredrag'; $group = 'Alle'; // MÃ¥lgruppe $price = 1; $homepage = 'http://kalender.vih.dk' . $this->url('../'); $email = '*****@*****.**'; $data = array('side' => 'arr', 'ArrKunstner' => $summary, 'ArrBeskrivelse' => $short_description, 'ArrLangBeskriv' => $long_description, 'ArrStartday' => $start_date_day, 'ArrStartmonth' => $start_date_month, 'ArrStartyear' => $start_date_year, 'ArrSlutday' => $end_date_day, 'ArrSlutmonth' => $end_date_month, 'ArrSlutyear' => $start_date_year, 'ArrTidspunkt' => $time, 'ArrUGenre' => $genre, 'ArrMaalgruppe' => $group, 'ArrPris' => 'Ukendt pris', 'ArrHomepage' => $homepage, 'ArrEmail' => $email); $data = array_map('utf8_decode', $data); $request->addPostParameter($data); $response = $request->send(); // @todo do some error checking $timestamp = date('YmdHis'); $request = new HTTP_Request2('http://www.kultunaut.dk/perl/arradd/type-nynaut/timestamp-' . $timestamp, HTTP_Request2::METHOD_POST); $data['side'] = 'sted'; $data['StedNr'] = $GLOBALS['kultunaut_place']; // Vejle Idrætshøjskole $data['SkiftArrang'] = 'no'; $data['adress'] = utf8_decode("Vejle Idrætshøjskole\nØrnebjergvej 28\n7100 Vejle"); $request->addPostParameter($data); $response = $request->send(); $body = $response->getBody(); // @todo do some error checking $xpath = new DOMXPath(@DOMDocument::loadHTML($body)); $event_id = $xpath->query("//input[@type='hidden' and @name='ArrNr']/@value")->item(0)->nodeValue; #4485217 $record = $this->event_gateway->fetch(array('gcal_event_id' => $this->context->getEventId(), "parameter" => 'kultunaut_event_id')); if (!empty($record)) { throw new Exception('Event has already been published'); } $this->event_gateway->insert(array('gcal_event_id' => $this->context->getEventId(), "parameter" => 'kultunaut_event_id', 'key' => $event_id)); $data['side'] = 'godkend'; $data['ArrNr'] = $event_id; $request = new HTTP_Request2('http://www.kultunaut.dk/perl/arradd/type-nynaut/timestamp-' . $timestamp . '/tak', HTTP_Request2::METHOD_POST); $request->addPostParameter($data); $response = $request->send(); if (!strpos($response->getBody(), 'TAK FOR INDTASTNINGEN')) { throw new Exception('Something went wrong on confirm'); } return new k_SeeOther($this->context->url(null, array('flare' => 'Event created: ' . $event_id))); }
/** * The actual method for sending requests * * @param string $url * @param array $headers * @param array $params * @return HTTP_Request2_Response */ protected function send($method, $url, array $params = array(), array $headers = array()) { $headers['GData-Version'] = '2'; $headers['User-Agent'] = 'Vivvo/' . VIVVO_VERSION . ' (' . self::$request_adapter . ') PHP/' . PHP_VERSION; $request = new HTTP_Request2($url); $request->setAdapter(self::$request_adapter); $request->setConfig('ssl_verify_peer', false); $request->setConfig('follow_redirects', true); $request->setHeader($headers); $request->setMethod($method); if ($method == HTTP_Request2::METHOD_POST) { $request->addPostParameter($params); } return $request->send(); }
/** * Creates a user and a HTTP_Request2 object, does a normal login * and prepares the cookies for the HTTP GET request object so that * the user is seen as logged in when requesting any HTML page. * * Useful for testing HTML pages or ajax URLs. * * @param string $urlSuffix Suffix for the URL * @param mixed $auth If user authentication is needed (true/false) * or array with username and password * @param boolean $privateKey True if to add user with private key * * @return array(HTTP_Request2, integer) HTTP request object and user id * * @uses getRequest() */ protected function getLoggedInRequest($urlSuffix = null, $auth = true, $privateKey = null) { if (is_array($auth)) { list($username, $password) = $auth; } else { $username = '******'; $password = '******'; } $uid = $this->addUser($username, $password, $privateKey); $req = new HTTP_Request2($GLOBALS['unittestUrl'] . '/login.php?unittestMode=1', HTTP_Request2::METHOD_POST); $cookies = $req->setCookieJar()->getCookieJar(); $req->addPostParameter('username', $username); $req->addPostParameter('password', $password); $req->addPostParameter('submitted', 'Log In'); $res = $req->send(); //after login, we normally get redirected $this->assertEquals(302, $res->getStatus(), 'Login failure'); $req = $this->getRequest($urlSuffix); $req->setCookieJar($cookies); return array($req, $uid); }
public function testPostParametersPrecedeSetBodyForPost() { $req = new HTTP_Request2('http://www.example.com/', HTTP_Request2::METHOD_POST); $req->setBody('Request body'); $req->addPostParameter('foo', 'bar'); $this->assertEquals('foo=bar', $req->getBody()); $req->setMethod(HTTP_Request2::METHOD_PUT); $this->assertEquals('Request body', $req->getBody()); }
/** * 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...'); } } } }
/** * Call any of the repustate.com APIs, even ones we do not yet * have a nice wrapper for, and get the results * * @param string $apiCall name of the API call to make * @param array $urlParams an array of params to pass to the API call * @param array $postParams an array of params to put in the body of the POST * @return array the results of calling the API */ public function genericApiJsonCall($apiCall, $urlParams, $postParams = null) { // step 1: build up the API URL $url = $this->buildApiUrl($apiCall, $urlParams, 'json'); // step 2: make the call if ($postParams == null) { $client = new \HTTP_Request2($url, \HTTP_Request2::METHOD_GET); } else { $client = new \HTTP_Request2($url, \HTTP_Request2::METHOD_POST); foreach ($postParams as $name => $value) { $client->addPostParameter($name, $value); } } // var_dump($url); $jsonResult = $client->send()->getBody(); // var_dump($jsonResult); $result = json_decode($jsonResult, true); var_dump($result); // step 3: was there an error at all? // if there was, this method will throw a suitable exception $this->checkResultForErrors($url, $result); // step 4: no error; return the result back to the caller // for further decoding return $result; }
protected function fetchResponse($license, $_CONFIG, $forceTemplate, $_CORELANG) { $v = preg_split('#\\.#', $_CONFIG['coreCmsVersion']); $e = $_CONFIG['coreCmsEdition']; $version = current($v); unset($v[key($v)]); foreach ($v as $part) { $version *= 100; $version += $part; } $srvUri = 'updatesrv1.contrexx.com'; $srvPath = '/'; $data = array('installationId' => $license->getInstallationId(), 'licenseKey' => $license->getLicenseKey(), 'edition' => $license->getEditionName(), 'version' => $this->coreCmsVersion, 'versionstate' => $this->coreCmsStatus, 'domainName' => $this->domainUrl, 'sendTemplate' => $forceTemplate); if (true) { try { $objFile = new \Cx\Lib\FileSystem\File(ASCMS_INSTANCE_PATH . ASCMS_INSTANCE_OFFSET . '/config/License.lic'); $rawData = $objFile->getData(); $response = json_decode(base64_decode($rawData)); } catch (\Cx\Lib\FileSystem\FileSystemException $e) { $license->setState(License::LICENSE_ERROR); $license->setGrayzoneMessages(array(\FWLanguage::getLanguageCodeById(LANG_ID) => new Message(\FWLanguage::getLanguageCodeById(LANG_ID), $_CORELANG['TXT_LICENSE_COMMUNICATION_ERROR']))); $license->check(); throw $e; } return $response; } $a = $_SERVER['REMOTE_ADDR']; $r = 'http://'; if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { $r = 'https://'; } $r .= $_SERVER['SERVER_NAME'] . ASCMS_INSTANCE_OFFSET; $request = new \HTTP_Request2('http://' . $srvUri . $srvPath . '?v=' . $version, \HTTP_Request2::METHOD_POST); $request->setHeader('X-Edition', $e); $request->setHeader('X-Remote-Addr', $a); $request->setHeader('Referer', $r); $jd = new \Cx\Core\Json\JsonData(); $request->addPostParameter('data', $jd->json($data)); try { $objResponse = $request->send(); if ($objResponse->getStatus() !== 200) { $license->setState(License::LICENSE_ERROR); $license->setGrayzoneMessages(array(\FWLanguage::getLanguageCodeById(LANG_ID) => new Message(\FWLanguage::getLanguageCodeById(LANG_ID), $_CORELANG['TXT_LICENSE_COMMUNICATION_ERROR']))); $license->check(); return null; } else { \DBG::dump($objResponse->getBody()); $response = json_decode($objResponse->getBody()); } } catch (\HTTP_Request2_Exception $objException) { $license->setState(License::LICENSE_ERROR); $license->setGrayzoneMessages(array(\FWLanguage::getLanguageCodeById(LANG_ID) => new Message(\FWLanguage::getLanguageCodeById(LANG_ID), $_CORELANG['TXT_LICENSE_COMMUNICATION_ERROR']))); $license->check(); throw $objException; } return $response; }