/** Generic request using the protocol:
  * POSTs data & files, checks the magic header
  * @param array $post Arbitrary data to POST
  * @param array $files Files to upload: { name: path | [path, filename] | [path, filename, mimetype] }
  * @return HttpResponse
  * @throws RemScriptProtocolError
  */
 function _request($post, $files)
 {
     # Prepare
     $request = new HttpRequest($this->script_url, 'POST');
     $request->mimicBrowser();
     $request->headers['Connection'] = 'Close';
     $request->post($post);
     if (!empty($files)) {
         foreach ($files as $name => $upload) {
             list($path, $filename, $mimetype) = (array) $upload + array(null, null, null);
             $request->upload($name, $path, $filename, $mimetype);
         }
     }
     # Request
     try {
         $response = $request->open();
     } catch (HttpRequestError $e) {
         throw new RemScriptProtocolError('Request error: ' . $e->getMessage(), RemScriptProtocolError::REQUEST_ERROR, $e);
     }
     # Response: check code
     if ($response->code != 200) {
         throw new RemScriptProtocolError('Response code: ' . $response->code);
     }
     # Response: check magic
     $expected = self::RESPONSE_MAGIC;
     $actual = fread($response->f, strlen($expected));
     if ($actual !== $expected) {
         throw new RemScriptProtocolError('Wrong magic: ' . var_export($actual, 1));
     }
     # All okay
     return $response;
 }
Ejemplo n.º 2
0
 function __construct(array $macros, IRouter $router, HttpRequest $req, I18n $i18n)
 {
     $this->router = $router;
     $this->url = $req->getUrl();
     $this->i18n = $i18n;
     $this->macros = $this->macros + $macros;
 }
Ejemplo n.º 3
0
 /**
  * Execute a HTTP request to MusicBrainz server, errorMessage attribute is set in case of error.
  *
  * @return bool|string MusicBrainz informations or false on failure
  */
 private function executeCall()
 {
     //request JSON output format
     $this->setRequestedFormat('json');
     //create a HTTP request object and call
     require_once $_SERVER['DOCUMENT_ROOT'] . '/server/lib/HttpRequest.php';
     $request = new HttpRequest();
     if (!$request->execute($this->endpoint, 'GET', null, null, $this->queryParameters, $response, $responseHeaders)) {
         $this->errorMessage = 'Error during request';
         //error during HTTP request
         return false;
     }
     //decode response
     if ($this->format === 'json') {
         $response = json_decode($response);
         if (json_last_error() !== JSON_ERROR_NONE) {
             $this->errorMessage = 'Invalid response received';
             //error on JSON parsing
             return false;
         }
         //return object
         return $response;
     }
     //return false by default
     return false;
 }
 public function request(array $params)
 {
     $request = new \HttpRequest($this->getTransmissionURL(), "POST");
     $request->addBody(json_encode($params));
     $this->client->attach($request);
     return $this->client->send();
 }
Ejemplo n.º 5
0
 /**
  * @param HttpRequest $request
  * @return string
  */
 protected static function chooseController(HttpRequest $request)
 {
     /* Get controller name from the request */
     $ctrl = $request->getController() . 'Controller';
     /* If this controller exists - pass it or use default MainController */
     return '\\application\\controllers\\' . (class_exists('\\application\\controllers\\' . $ctrl) ? $ctrl : 'MainController');
 }
Ejemplo n.º 6
0
 /**
  * Examine the URL, optionally looking for a specific service. If no
  * service selection is done, all the services that the URL publishes
  * will be returned.
  *
  * @param string $url The URL to explore
  * @param string $service The service to look for
  * @return array An array of the exposed services at the URL
  */
 function discover($url, $services = null)
 {
     // Perform the query
     $ret = new HttpRequest($url);
     // Grab the data
     $status = $ret->status();
     $content = $ret->responseText();
     $headers = $ret->headers();
     $results = array();
     // Enumerate the explorers
     $explorers = config::get(Discovery::KEY_EXPLORERS, array());
     foreach ($explorers as $explorer) {
         // Discover the service and merge the results
         $instance = new $explorer($url, $headers, $content);
         $instance->discover();
         if ($services) {
             foreach ($instance->getAllServices() as $stype => $sdata) {
                 // Return the service if it matches the type.
                 if ($stype == $service) {
                     return $sdata;
                 }
             }
         } else {
             // Merge the resultset otherwise
             $results = array_merge($results, $instance->getAllServices());
         }
     }
     // Return null if we were looking for a specific service
     if ($services) {
         return null;
     }
     return $results;
 }
Ejemplo n.º 7
0
 /**
  * Appends the necessary Custom Authentication credentials for making this authorized call
  * @param HttpRequest $request The out going request to access the resource
  */
 public static function appendCustomAuthParams($request)
 {
     $arrHeaders = $request->__get('headers');
     $arrAuthHeader = array("X-Auth-Token" => Configuration::$APITOKEN);
     $arrHeaders = array_merge($arrHeaders, $arrAuthHeader);
     $request->__set('headers', $arrHeaders);
 }
Ejemplo n.º 8
0
 protected function makeApiRequest($type, $action, $params, $format = null, $creds = null, $useCache = true)
 {
     $config = load_class('Config');
     $url = $config->config['base_url'] . 'api/' . urlencode($type);
     $useCache = false;
     // $creds === false means don't use credentials
     // $creds === null  means use default credentials
     // $creds === array($user, $pass) otherwise (where pass is md5)
     // TODO pull this from config or make default user
     if ($creds === null) {
         // TODO find a better solution here !!!
         if (!array_key_exists('api_creds_user', $config->config)) {
             $config->config['api_creds_user'] = '******';
         }
         if (!array_key_exists('api_creds_token', $config->config)) {
             $config->config['api_creds_token'] = '6228bd57c9a858eb305e0fd0694890f7';
         }
         $creds = array($config->config['api_creds_user'], $config->config['api_creds_token']);
     }
     $req = new StdClass();
     $req->request = new StdClass();
     if (is_array($creds)) {
         $req->request->auth = new StdClass();
         $req->request->auth->user = $creds[0];
         $req->request->auth->pass = $creds[1];
     }
     $req->request->action->type = $action;
     if (is_array($params)) {
         $req->request->action->data = new StdClass();
         foreach ($params as $k => $v) {
             $req->request->action->data->{$k} = $v;
         }
     }
     $payload = $this->encode_request($req, $format);
     $cache_filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'joindin-test-' . md5($url . $payload);
     if ($useCache) {
         // Check for reading from cache
         if (file_exists($cache_filename) && is_readable($cache_filename)) {
             $cache_data = json_decode(file_get_contents($cache_filename));
             if (time() < $cache_data->expires) {
                 return $cache_data->payload;
             }
         }
     }
     $request = new HttpRequest($url, HttpRequest::METH_POST);
     $request->setBody($payload);
     if ($format == 'xml') {
         $request->setHeaders(array('Content-Type' => 'text/xml'));
     } else {
         // json is the default
         $request->setHeaders(array('Content-Type' => 'application/json'));
     }
     $response = $request->send();
     if ($useCache) {
         $cache_data = json_encode(array('payload' => $response->getBody(), 'expires' => time() + 3600));
         file_put_contents($cache_filename, $cache_data);
         // chmod( $cache_filename, 0777 );
     }
     return $response->getBody();
 }
Ejemplo n.º 9
0
 /**
  * Performs the test.
  *
  * @return \Jyxo\Beholder\Result
  */
 public function run()
 {
     // The http extension is required
     if (!extension_loaded('http')) {
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::NOT_APPLICABLE, 'Extension http missing');
     }
     $http = new \HttpRequest($this->url, \HttpRequest::METH_GET, array('connecttimeout' => 5, 'timeout' => 10, 'useragent' => 'JyxoBeholder'));
     try {
         $http->send();
         if (200 !== $http->getResponseCode()) {
             throw new \Exception(sprintf('Http error: %s', $http->getResponseCode()));
         }
         if (isset($this->tests['body'])) {
             $body = $http->getResponseBody();
             if (!preg_match($this->tests['body'], $body)) {
                 $body = trim(strip_tags($body));
                 throw new \Exception(sprintf('Invalid body: %s', \Jyxo\String::cut($body, 16)));
             }
         }
         // OK
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::SUCCESS);
     } catch (\HttpException $e) {
         $inner = $e;
         while (null !== $inner->innerException) {
             $inner = $inner->innerException;
         }
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, $inner->getMessage());
     } catch (\Exception $e) {
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, $e->getMessage());
     }
 }
 public function testDeleteAsset()
 {
     $assetID = file_get_contents('test.assetid');
     $r = new HttpRequest($this->server_url . $assetID, HttpRequest::METH_DELETE);
     $r->send();
     $this->assertEquals(200, $r->getResponseCode());
 }
Ejemplo n.º 11
0
 public function loginAction()
 {
     $this->view->disable();
     $http_request = new HttpRequest();
     print_r($_SERVER);
     $header = array('Host:106.37.195.128', 'User-Agent:Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0', 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Referer:http://106.37.195.128/chinalifepcsfa/system/userLogin.do', 'Connection:keep-alive');
     $data = 'platformType=0&userId=530123197902182620&password=sp182620';
     $http_respone = $http_request->post('http://106.37.195.128/chinalifepcsfa/system/userLogin.do', $header, $data);
     if (isset($http_respone->headers['Location'])) {
         $location = $http_respone->headers['Location'];
         $cookies = $http_respone->cookies;
         $header2 = array('Host:106.37.195.128', 'User-Agent:Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0', 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Referer:http://106.37.195.128/chinalifepcsfa/system/userLogin.do', 'Connection:keep-alive');
         $http_respone2 = $http_request->get($location, $header2, $cookies);
         preg_match('@href="(/chinalifepcsfa/user/electronicInsurance.do\\?.*)"@Ui', $http_respone2->content, $matches);
         $entrance_href = 'http://106.37.195.128' . $matches[1];
         $header3 = array('Host:106.37.195.128', 'User-Agent:Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0', 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Connection:keep-alive');
         $http_respone3 = $http_request->get($entrance_href, $header3, $cookies);
         $final_url = $http_respone3->headers['Location'];
         $_SESSION['emu_url'] = $final_url;
         $final_header = array('Host:106.37.195.128:7011', 'User-Agent:Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0', 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Connection:keep-alive');
         $final_http_response = $http_request->get($final_url, $final_header, $cookies);
         $_SESSION['emu_cookies'] = $final_http_response->cookies;
     } else {
         echo json_encode(array('success' => false, 'err_msg' => '用户名或密码错误!'));
     }
 }
Ejemplo n.º 12
0
 public function keyword_search($keyword)
 {
     // 從 Google 取得搜尋結果(HTML原始碼)
     $keyword = urlencode($keyword);
     $url = "https://www.google.com.tw/webhp?hl=zh-TW#hl=zh-TW&q={$keyword}&num=10";
     $httpReq = new HttpRequest();
     $httpReq->setUrl($url);
     $content = $httpReq->submit();
     unset($httpReq);
     $results = array();
     // 分析原始碼並取得每個項目
     if (preg_match_all('/<!--m-->(.*?)<!--n-->/s', $content, $items)) {
         $idx = 0;
         foreach ($items[1] as $key => $item) {
             $resultItem = new ResultItem();
             $resultItem->sequence = $idx + 1;
             $resultItem->title = preg_match('/<a .*?>(.*?)<\\/a>/s', $item, $res) ? trim($res[1]) : "";
             $resultItem->link = urldecode(preg_match('/<h3 class="r"><a href="(.*?)".*?>.*?<\\/a>/s', $item, $res) ? trim($res[1]) : "");
             $resultItem->description = preg_match('/<span class="st">(<span class="f">(.*?)<\\/span>)?(.*?)<\\/span>/s', $item, $res) ? trim($res[3]) : "";
             $resultItem->save_date = str_replace(" - ", "", $res[2]);
             if (trim($resultItem->link) == "") {
                 continue;
             }
             $idx++;
             $results[] = $resultItem;
         }
     }
     return $results;
 }
Ejemplo n.º 13
0
 protected function request($method, $uri, $args)
 {
     $parsedUrl = parse_url($this->ec2Url);
     $uri = "{$parsedUrl['path']}{$uri}";
     $HttpRequest = new HttpRequest();
     $HttpRequest->setOptions(array("useragent" => "Scalr (https://scalr.net)"));
     $args['Version'] = $this->apiVersion;
     $args['SignatureVersion'] = 2;
     $args['SignatureMethod'] = "HmacSHA256";
     $args['Timestamp'] = $this->getTimestamp();
     $args['AWSAccessKeyId'] = $this->accessKeyId;
     ksort($args);
     foreach ($args as $k => $v) {
         $CanonicalizedQueryString .= "&{$k}=" . rawurlencode($v);
     }
     $CanonicalizedQueryString = trim($CanonicalizedQueryString, "&");
     $url = $parsedUrl['port'] ? "{$parsedUrl['host']}:{$parsedUrl['port']}" : "{$parsedUrl['host']}";
     $args['Signature'] = $this->getSignature(array($method, $url, $uri, $CanonicalizedQueryString));
     $HttpRequest->setUrl("{$parsedUrl['scheme']}://{$url}{$uri}");
     $HttpRequest->setMethod(constant("HTTP_METH_{$method}"));
     if ($args) {
         if ($method == 'POST') {
             $HttpRequest->setPostFields($args);
             $HttpRequest->setHeaders(array('Content-Type' => 'application/x-www-form-urlencoded'));
         } else {
             $HttpRequest->addQueryData($args);
         }
     }
     try {
         $HttpRequest->send();
         $data = $HttpRequest->getResponseData();
         if ($HttpRequest->getResponseCode() == 200) {
             $response = simplexml_load_string($data['body']);
             if ($this->responseFormat == 'Object') {
                 $json = @json_encode($response);
                 $response = @json_decode($json);
             }
             if ($response->Errors) {
                 throw new Exception($response->Errors->Error->Message);
             } else {
                 return $response;
             }
         } else {
             $response = @simplexml_load_string($data['body']);
             if ($response) {
                 throw new Exception($response->Error->Message);
             }
             throw new Exception(trim($data['body']));
         }
         $this->LastResponseHeaders = $data['headers'];
     } catch (Exception $e) {
         if ($e->innerException) {
             $message = $e->innerException->getMessage();
         } else {
             $message = $e->getMessage();
         }
         throw new Exception($message);
     }
 }
Ejemplo n.º 14
0
 /**
  * @param HttpRequest $request
  * @return mixed
  */
 public function handleRequest(HttpRequest $request)
 {
     if ($request->getCode() >= HttpRequest::HTTP_CLIENT_ERROR && $request->getCode() < HttpRequest::HTTP_SERVER_ERROR) {
         echo 'Handling client error request';
     } else {
         parent::handleRequest($request);
     }
 }
Ejemplo n.º 15
0
 public function index()
 {
     $http_request = new HttpRequest();
     $http_response = $http_request->get('www.sina.com');
     $http_response->headers;
     $user = UserModel::findUserById('*****@*****.**');
     $this->view->setVars(array('headers' => $http_response->headers, 'content' => htmlspecialchars($http_response->content), 'user' => $user));
 }
Ejemplo n.º 16
0
 public function fromUrl($url)
 {
     $this->url = $url;
     //		ブログによっては403ではじかれる。ユーザーエージェント?IP?
     $httpRequest = new HttpRequest($this->url);
     $httpRequest->exec();
     $this->fromText($url, $httpRequest->getResponse());
 }
Ejemplo n.º 17
0
 /**
  * @param HttpRequest $request
  * @return mixed
  */
 public function handleRequest(HttpRequest $request)
 {
     if ($request->getCode() >= HttpRequest::HTTP_SERVER_ERROR) {
         echo 'Handling server error request';
     } else {
         parent::handleRequest($request);
     }
 }
Ejemplo n.º 18
0
 function ModifyClass($secretAcessKey, $access_key, $webServiceUrl, $array = array())
 {
     require_once "AuthBase.php";
     $authBase = new AuthBase($secretAcessKey, $access_key);
     $method = "modify";
     $requestParameters["signature"] = $authBase->GenerateSignature($method, $requestParameters);
     $requestParameters["class_id"] = $array['class_id'];
     $requestParameters["start_time"] = $array['start_time'];
     $requestParameters["title"] = $array['title'];
     //Required
     $requestParameters["duration"] = $array['duration'];
     //optional
     $requestParameters["time_zone"] = "Africa/Cairo";
     //optional
     $requestParameters["attendee_limit"] = $array['name'];
     //optional
     $requestParameters["control_category_id"] = "";
     //optional
     $requestParameters["create_recording"] = "";
     //optional
     $requestParameters["return_url"] = "";
     //optional
     $requestParameters["status_ping_url"] = "";
     //optional
     $requestParameters["language_culture_name"] = "ar-SA";
     $httpRequest = new HttpRequest();
     try {
         $XMLReturn = $httpRequest->wiziq_do_post_request($webServiceUrl . '?method=modify', http_build_query($requestParameters, '', '&'));
     } catch (Exception $e) {
         echo $e->getMessage();
     }
     if (!empty($XMLReturn)) {
         try {
             $objDOM = new DOMDocument();
             $objDOM->loadXML($XMLReturn);
         } catch (Exception $e) {
             echo $e->getMessage();
         }
         $status = $objDOM->getElementsByTagName("rsp")->item(0);
         $attribNode = $status->getAttribute("status");
         if ($attribNode == "ok") {
             $this->result['state'] = 1;
             $this->result['id'] = $array['class_id'];
             $methodTag = $objDOM->getElementsByTagName("method");
             echo "method=" . ($method = $methodTag->item(0)->nodeValue);
             $modifyTag = $objDOM->getElementsByTagName("modify")->item(0);
             echo "<br>modify=" . ($modify = $modifyTag->getAttribute("status"));
         } else {
             if ($attribNode == "fail") {
                 $this->result['state'] = 0;
                 $error = $objDOM->getElementsByTagName("error")->item(0);
                 echo "<br>errorcode=" . ($errorcode = $error->getAttribute("code"));
                 echo "<br>errormsg=" . ($errormsg = $error->getAttribute("msg"));
             }
         }
     }
     //end if
 }
Ejemplo n.º 19
0
function cb_get_pois($params)
{
    $base_addr = 'http://orion.lab.fi-ware.org:1026/v1/queryContext';
    $limit = 1000;
    try {
        $orion_key = json_decode(file_get_contents('../orion_key.txt'))[0];
    } catch (Exception $ex) {
        $orion_key = "";
    }
    $search_area = cb_search_area($params);
    $ans = array();
    $next = 0;
    $more = TRUE;
    try {
        while ($more) {
            $more = FALSE;
            $addr = $base_addr . '?';
            if ($next > 0) {
                $addr = $addr . 'offset=' . $next . '&';
            }
            $addr = $addr . 'limit=' . $limit;
            $next = $next + $limit;
            $http = new HttpRequest($addr, HTTP_METH_POST);
            $headers = array();
            $headers['Content-Type'] = 'application/json';
            $headers['Accept'] = 'application/json';
            if ($orion_key != "") {
                $headers['X-Auth-Token'] = $orion_key;
            }
            $http->setHeaders($headers);
            $body = '{"entities":[{"type":"cie_poi","isPattern":"true","id":"cie_poi_*' . '"}],"attributes":["data"],"restriction":{"scopes":[{"type":"FI' . 'WARE::Location","value":' . $search_area . '}]}}';
            $http->setBody($body);
            $respmsg = $http->send();
            $resp_str = $respmsg->getBody();
            $resp = json_decode($resp_str);
            if (property_exists($resp, 'contextResponses')) {
                $context_responses = $resp->contextResponses;
                foreach ($context_responses as $context_response) {
                    $more = TRUE;
                    $context_element = $context_response->contextElement;
                    $id = $context_element->id;
                    $uuid = substr($id, 8);
                    $attributes = $context_element->attributes;
                    foreach ($attributes as $attribute) {
                        $name = $attribute->name;
                        if ($name == 'data') {
                            $encoded_value = $attribute->value;
                            $json_value = rawurldecode($encoded_value);
                            $ans[$uuid] = json_decode($json_value, TRUE);
                        }
                    }
                }
            }
        }
    } catch (Exception $e) {
    }
    return $ans;
}
Ejemplo n.º 20
0
 /**
  * @param HttpRequest $request
  * @return mixed
  */
 public function handleRequest(HttpRequest $request)
 {
     if ($request->getCode() < HttpRequest::HTTP_CLIENT_ERROR && $request->getCode() >= HttpRequest::HTTP_OK) {
         echo 'Handling successful request';
         return true;
     } else {
         parent::handleRequest($request);
     }
 }
Ejemplo n.º 21
0
 public function test()
 {
     $httpRequest = new HttpRequest(self::URL_UTF8);
     $ret = $httpRequest->exec();
     $this->assertEquals($ret, true);
     $httpRequest = new HttpRequest(self::URL_EUC_JP);
     $ret = $httpRequest->exec();
     $this->assertEquals($ret, true);
 }
 /**
  * @return HttpUrl
  **/
 protected function processPath(HttpRequest $request)
 {
     if ($request->hasServerVar('REQUEST_URI')) {
         $path = $this->getPath(HttpUrl::create()->parse($request->getServerVar('REQUEST_URI')));
     } else {
         throw new RouterException('Cannot resolve path');
     }
     return $path;
 }
Ejemplo n.º 23
0
 public function index($token)
 {
     $app_id = M('Wxuser')->where(array('token' => $token))->getField('fuwuappid');
     if ($_GET['auth_code'] == '') {
         $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
         $api_url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=' . $app_id . '&auth_skip=false&scope=auth_userinfo,auth_contact&redirect_uri=' . urlencode($redirect_uri);
         echo '<script>window.location.href=\'' . $api_url . '\'</script>';
     } else {
         $auth_code = $_GET['auth_code'];
         $fuwuurl = 'https://openapi.alipay.com/gateway.do';
         $fuwudata = array('app_id' => $app_id, 'method' => 'alipay.system.oauth.token', 'charset' => 'UTF-8', 'sign_type' => 'RSA', 'timestamp' => date('Y-m-d H:i:s', time()), 'version' => '1.0', 'grant_type' => 'authorization_code', 'code' => $auth_code);
         require './PigCms/Lib/ORG/Fuwu/config.php';
         $AlipaySign = new AlipaySign();
         ksort($fuwudata);
         $params = array();
         foreach ($fuwudata as $key => $value) {
             $params[] = $key . '=' . $value;
         }
         $fuwudata_build = implode('&', $params);
         $fuwudata['sign'] = $AlipaySign->rsa_sign($fuwudata_build, $config['merchant_private_key_file']);
         $re = new HttpRequest();
         $fuwu_result = $re->sendPostRequst($fuwuurl, $fuwudata);
         $return = json_decode(iconv('GBK', 'UTF-8', $fuwu_result), true);
         if ($return['alipay_system_oauth_token_response']['access_token'] != '') {
             $auth_token = $return['alipay_system_oauth_token_response']['access_token'];
             $userinfo_url = 'https://openapi.alipay.com/gateway.do';
             $userinfo_data = array('app_id' => $app_id, 'method' => 'alipay.user.userinfo.share', 'charset' => 'GBK', 'sign_type' => 'RSA', 'timestamp' => date('Y-m-d H:i:s', time()), 'version' => '1.0', 'auth_token' => $auth_token);
             ksort($userinfo_data);
             $params2 = array();
             foreach ($userinfo_data as $key2 => $value2) {
                 $params2[] = $key2 . '=' . $value2;
             }
             $userinfo_data_build = implode('&', $params2);
             $userinfo_data['sign'] = $AlipaySign->rsa_sign($userinfo_data_build, $config['merchant_private_key_file']);
             $userinfo_result = $re->sendPostRequst($userinfo_url, $userinfo_data);
             $userinfo_return = json_decode(iconv('GBK', 'UTF-8', $userinfo_result), true);
             if ($userinfo_return['alipay_user_userinfo_share_response']['user_id'] != '') {
                 $m_fuwuuser = M('fuwuuser');
                 $where_fuwuuser['wecha_id'] = 'z_' . md5($userinfo_return['alipay_user_userinfo_share_response']['user_id']);
                 $where_fuwuuser['token'] = $token;
                 $fuwuuser = $m_fuwuuser->where($where_fuwuuser)->find();
                 if ($fuwuuser == '') {
                     $add_fuwuuser = $userinfo_return['alipay_user_userinfo_share_response'];
                     $add_fuwuuser['wecha_id'] = 'z_' . md5($userinfo_return['alipay_user_userinfo_share_response']['user_id']);
                     $add_fuwuuser['token'] = $token;
                     $add_fuwuuser['addtime'] = time();
                     $id_fuwuuser = $m_fuwuuser->add($add_fuwuuser);
                 } else {
                     $save_fuwuuser = $userinfo_return['alipay_user_userinfo_share_response'];
                     $update_fuwuuser = $m_fuwuuser->where($where_fuwuuser)->save($save_fuwuuser);
                 }
                 $wecha_id = 'z_' . md5($userinfo_return['alipay_user_userinfo_share_response']['user_id']);
                 return $wecha_id;
             }
         }
     }
 }
Ejemplo n.º 24
0
 public static function execute($parameters)
 {
     $h = new \HttpRequest($parameters['server']['scheme'] . '://' . $parameters['server']['host'] . $parameters['server']['path'] . (isset($parameters['server']['query']) ? '?' . $parameters['server']['query'] : ''), static::$_methods[$parameters['method']], array('redirect' => 5));
     if ($parameters['method'] == 'post') {
         $h->setRawPostData($parameters['parameters']);
     }
     $h->send();
     return $h->getResponseBody();
 }
Ejemplo n.º 25
0
/**
 * 2012年6月28日 携程 唐春龙 研发中心
 * 通过httpRequest调用远程webservice服务(返回一个XML)
 * @param $responseUrl 远程服务的地址
 * @param $requestXML 远程服务的参数请求体XML
 * @param 返回XML
 */
function httpRequestSoapData($responseUrl, $requestXML)
{
    try {
        $myhttp = new HttpRequest($responseUrl . "?WSDL", "POST");
        //--相对于API2.0固定
        $r_head = <<<BEGIN
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Request xmlns="http://ctrip.com/">
<requestXML>
BEGIN;
        //--相对于API2.0固定
        $r_end = <<<BEGIN
</requestXML>
</Request>
</soap:Body>
</soap:Envelope>
BEGIN;
        //返回头--相对于API2.0固定
        $responseHead = <<<begin
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><RequestResponse xmlns="http://ctrip.com/"><RequestResult>
begin;
        //返回尾--相对于API2.0固定
        $responseEnd = <<<begin
</RequestResult></RequestResponse></soap:Body></soap:Envelope>
begin;
        $requestXML = str_replace("<", @"&lt;", $requestXML);
        $requestXML = str_replace(">", @"&gt;", $requestXML);
        $requestXML = $r_head . $requestXML . $r_end;
        //echo "<!--" . $requestXML ."-->";
        $myhttp->open();
        $myhttp->send($requestXML);
        $responseBodys = $myhttp->getResponseBody();
        //这里有可能有HEAD,要判断一下
        if (strpos($responseBodys, "Content-Type: text/xml; charset=utf-8")) {
            $coutw = $myhttp->responseBodyWithoutHeader;
        } else {
            $coutw = $responseBodys;
        }
        //$myhttp->responseBodyWithoutHeader;
        //$coutw=$myhttp->responseBodyWithoutHeader;
        $coutw = str_replace($responseHead, "", $coutw);
        //替换返回头
        $coutw = str_replace($responseEnd, "", $coutw);
        //替换返回尾
        $coutw = str_replace("&lt;", "<", $coutw);
        //将符号换回来
        $coutw = str_replace("&gt;", ">", $coutw);
        //将符号换回来
        // echo $coutw;
        return $coutw;
    } catch (SoapFault $fault) {
        return $fault->faultcode;
    }
}
Ejemplo n.º 26
0
 /**
  * @param HttpRequest $request
  * @return mixed
  * Function is to set language.
  * Default 'en_US'
  */
 public function setLanguage(HttpRequest $request)
 {
     $language = $request->param('language');
     if (array_key_exists($language, self::$allowed_languages)) {
         Session::set('language', self::$allowed_languages[$language]['locale']);
     } else {
         Session::set('language', 'en_US');
     }
     return $this->redirectBack();
 }
Ejemplo n.º 27
0
 function getUserMeta()
 {
     $url = "http://api.twitter.com/1/users/show.json?screen_name=" . $this->user;
     $r = new HttpRequest("get", $url);
     if ($r->getError()) {
         $this->error("Could not get user information");
     } else {
         return json_decode($r->getResponse(), true);
     }
 }
Ejemplo n.º 28
0
function returnWord()
{
    $r = new HttpRequest('http://randomword.setgetgo.com/get.php?len=6', "GET");
    $r->send();
    if ($r->getStatus() == 200) {
        return $_SESSION["word"] = $r->getResponseBody();
    } else {
        return "cannot generate music";
    }
}
    public function test()
    {
        $route = 'http://localhost/wordpress/augsburg/de/wp-json/extensions/v0/
					modified_content/posts_and_pages';
        $r = new HttpRequest($route, HttpRequest::METH_GET);
        $r->addQueryData(array('since' => '2000-01-01T00:00:00Z'));
        $r->send();
        $this->assertEquals(200, $r->getResponseCode());
        $body = $r->getResponseBody();
    }
Ejemplo n.º 30
0
 /**
  * {@inheritdoc}
  */
 public function call()
 {
     $method = $this->request->getMethod();
     $call = strtolower($method);
     $params = $this->params($method);
     if ($params === false || $params === null || !is_callable(array($this, $call))) {
         throw new GraphException("Method not allowed", HttpResponse::HTTP_METHOD_NOT_ALLOWED);
     }
     return $this->{$call}(new ParameterBag((array) $params));
 }