/** * Issues request and returns response as an array decoded according to the * response's content type if the response code is 200, else triggers the * $model->onError() method (if it exists) and finally returns false. * * @param mixed $model Either a CakePHP model with a request property, or an * array in the format expected by HttpSocket::request or a string which is a * URI. * @return mixed The response or false */ public function request(&$model) { if (is_object($model)) { $request = $model->request; } elseif (is_array($model)) { $request = $model; } elseif (is_string($model)) { $request = array('uri' => $model); } // Remove unwanted elements from request array $request = array_intersect_key($request, $this->Http->request); // Issues request $response = $this->Http->request($request); // Get content type header $contentType = $this->Http->response['header']['Content-Type']; // Extract content type from content type header if (preg_match('/^([a-z0-9\\/\\+]+);\\s*charset=([a-z0-9\\-]+)/i', $contentType, $matches)) { $contentType = $matches[1]; $charset = $matches[2]; } // Decode response according to content type switch ($contentType) { case 'application/xml': case 'application/atom+xml': case 'application/rss+xml': // If making multiple requests that return xml, I found that using the // same Xml object with Xml::load() to load new responses did not work, // consequently it is necessary to create a whole new instance of the // Xml class. This can use a lot of memory so we have to manually // garbage collect the Xml object when we've finished with it, i.e. got // it to transform the xml string response into a php array. App::import('Core', 'Xml'); $Xml = new Xml($response); $response = $Xml->toArray(false); // Send false to get separate elements $Xml->__destruct(); $Xml = null; unset($Xml); break; case 'application/json': case 'text/javascript': $response = json_decode($response, true); break; } if (is_object($model)) { $model->response = $response; } // Check response status code for success or failure if (substr($this->Http->response['status']['code'], 0, 1) != 2) { if (is_object($model) && method_exists($model, 'onError')) { $model->onError(); } return false; } return $response; }
/** * {@inheritdoc} */ protected function doSendInternalRequest(InternalRequestInterface $internalRequest) { $this->httpSocket->config['timeout'] = $this->getConfiguration()->getTimeout(); $request = array('version' => $this->getConfiguration()->getProtocolVersion(), 'redirect' => false, 'uri' => $url = (string) $internalRequest->getUrl(), 'method' => $internalRequest->getMethod(), 'header' => $this->prepareHeaders($internalRequest), 'body' => $this->prepareBody($internalRequest)); try { $response = $this->httpSocket->request($request); } catch (\Exception $e) { throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage()); } if (($error = $this->httpSocket->lastError()) !== null) { throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $error); } return $this->getConfiguration()->getMessageFactory()->createResponse((int) $response->code, $response->reasonPhrase, ProtocolVersionExtractor::extract($response->httpVersion), $response->headers, BodyNormalizer::normalize($response->body, $internalRequest->getMethod())); }
public function index() { $HttpSocket = new HttpSocket (); if (sizeof ( $this->params ['pass'] [0] ) != 1) { throw new InvalidArgumentException (); } if (! empty ( $_SERVER ['PHP_AUTH_USER'] ) && ! empty ( $_SERVER ['PHP_AUTH_PW'] )) { $HttpSocket->configAuth ( 'Basic', $_SERVER ['PHP_AUTH_USER'], $_SERVER ['PHP_AUTH_PW'] ); } elseif (isset ( $this->CurrentUser )) { $HttpSocket->configAuth ( 'Basic', $this->Session->read ( 'Auth.User.Login' ), $this->Session->read ( 'Auth.User.Password' ) ); } $this->response->type ( 'json' ); $request = array ( 'method' => env ( 'REQUEST_METHOD' ), 'body' => $this->request->data, 'uri' => array ( 'scheme' => Configure::read ( 'Api.scheme' ), 'host' => Configure::read ( 'Api.host' ), 'port' => 80, 'path' => Configure::read ( 'Api.path' ) . $this->params ['pass'] [0], 'query' => $this->params->query ) ); $response = $HttpSocket->request ( $request ); $this->response->statusCode ( $response->code ); $this->response->body ( $response->body ); return $this->response; }
protected function _request($path, $request = array()) { // preparing request $request = Hash::merge($this->_request, $request); $request['uri']['path'] .= $path; // Read cached GET results if ($request['method'] == 'GET') { $cacheKey = $this->_generateCacheKey(); $results = Cache::read($cacheKey); if ($results !== false) { return $results; } } // createding http socket object for later use $HttpSocket = new HttpSocket(); // issuing request $response = $HttpSocket->request($request); // olny valid response is going to be parsed if (substr($response->code, 0, 1) != 2) { if (Configure::read('debugApis')) { debug($request); debug($response->body); } return false; } // parsing response $results = $this->_parseResponse($response); // cache and return results if ($request['method'] == 'GET') { Cache::write($cacheKey, $results); } return $results; }
protected function _request($method, $params = array(), $request = array()) { // preparing request $query = Hash::merge(array('method' => $method, 'format' => 'json'), $params); $request = Hash::merge($this->_request, array('uri' => array('query' => $query)), $request); // Read cached GET results if ($request['method'] == 'GET') { $cacheKey = $this->_generateCacheKey(); $results = Cache::read($cacheKey); if ($results !== false) { return $results; } } // createding http socket object with auth configuration $HttpSocket = new HttpSocket(); $HttpSocket->configAuth('OauthLib.Oauth', array('Consumer' => array('consumer_token' => $this->_config['key'], 'consumer_secret' => $this->_config['secret']), 'Token' => array('token' => $this->_config['token'], 'secret' => $this->_config['secret2']))); // issuing request $response = $HttpSocket->request($request); // olny valid response is going to be parsed if ($response->code != 200) { if (Configure::read('debugApis')) { debug($request); debug($response->body); } return false; } // parsing response $results = $this->_parseResponse($response); // cache and return results if ($request['method'] == 'GET') { Cache::write($cacheKey, $results); } return $results; }
protected function _request($path, $request = array()) { // preparing request $request = Hash::merge($this->_request, $request); $request['uri']['path'] .= $path; if (isset($request['uri']['query'])) { $request['uri']['query'] = array_merge(array('access_token' => $this->_config['token']), $request['uri']['query']); } else { $request['uri']['query'] = array('access_token' => $this->_config['token']); } // createding http socket object for later use $HttpSocket = new HttpSocket(array('ssl_verify_host' => false)); // issuing request $response = $HttpSocket->request($request); // olny valid response is going to be parsed if (substr($response->code, 0, 1) != 2) { if (Configure::read('debugApis')) { debug($request); debug($response->body); die; } return false; } // parsing response $results = $this->_parseResponse($response); if (isset($results['data'])) { return $results['data']; } return $results; }
/** * Submits a request to Stripe. Requests are merged with default values, such as * the api host. If an error occurs, it is stored in `$lastError` and `false` is * returned. * * @param array $request Request details * @return mixed `false` on failure, data on success */ public function request($request = array()) { $this->lastError = null; $this->request = array('uri' => array('host' => 'api.stripe.com', 'scheme' => 'https', 'path' => '/'), 'method' => 'GET'); $this->request = Set::merge($this->request, $request); $this->request['uri']['path'] = '/v1/' . trim($this->request['uri']['path'], '/'); $this->Http->configAuth('Basic', $this->config['api_key'], ''); try { $response = $this->Http->request($this->request); switch ($this->Http->response['status']['code']) { case '200': return json_decode($response, true); break; case '400': $error = json_decode($response, true); $this->lastError = $error['error']['message']; return false; break; case '402': $error = json_decode($response, true); $this->lastError = $error['error']['message']; return false; break; default: $this->lastError = 'Unexpected error.'; CakeLog::write('stripe', $this->lastError); return false; break; } } catch (CakeException $e) { $this->lastError = $e->message; CakeLog::write('stripe', $e->message); } }
/** * Performs an API request to Basecamp * @param string $url * @param string $method * @param array $options * @return string * @access protected */ protected function _request($url, $method = 'GET', $options = array()) { // Extract our settings and create our HttpSocket extract($this->settings); $socket = new HttpSocket(); // Build, execute and return the response return $socket->request(am(array('method' => $method, 'uri' => array('scheme' => 'http', 'host' => $account . '.' . 'campfirenow.com', 'path' => $url, 'user' => $token, 'pass' => 'X'), 'auth' => array('method' => 'Basic', 'user' => $token, 'pass' => 'X'), 'header' => array('User-Agent' => 'CakePHP CampfireComponent')), $options)); }
function greet($peer_address = null, $peer_port = null, $data = array()) { if (!$peer_address || !$peer_port) { return true; } App::import('Core', 'HttpSocket'); $HttpSocket = new HttpSocket(); $req = array('method' => 'POST', 'uri' => array('scheme' => 'http', 'host' => $peer_address, 'port' => $peer_port, 'path' => '/peers/hello'), 'header' => array('User-Agent' => 'Gitrbug/0.2'), 'body' => array('data' => $data)); $res = $HttpSocket->request($req); return json_decode($res, true); }
function updateMyIP() { $addr = $this->findByName('ip_addr', array('fields' => 'value')); App::import('Core', 'HttpSocket'); $HttpSocket = new HttpSocket(); $res = $HttpSocket->request(array('method' => 'GET', 'uri' => array('scheme' => 'http', 'host' => 'ipinfodb.com', 'path' => '/ip_query.php', 'query' => 'output=json'), 'header' => array('User-Agent' => 'Gitrbug/0.2'))); $r = json_decode($res, true); if (empty($addr)) { $this->create(); $this->save(array('name' => 'ip_addr', 'value' => $r['Ip'])); } else { $this->updateAll(array('value' => $r['Ip']), array('name' => 'ip_addr')); } return $r['Ip']; }
/** * Makes the HTTP Rest request * * @return void * @author Rob Mcvey **/ public function handleRequest($request) { // HttpSocket. if (!$this->HttpSocket) { $this->HttpSocket = new HttpSocket(); $this->HttpSocket->quirksMode = true; // Amazon returns sucky XML } // Make request try { return $this->HttpSocket->request($request); } catch (SocketException $e) { // If error Amazon returns garbage XML and // throws HttpSocket::_decodeChunkedBody - Could not parse malformed chunk ??? throw new AmazonS3Exception(__('Could not complete the HTTP request')); } }
public function run($data) { if (!$data['hash']) { $this->err("Tried to run search without a hash!?"); debug($data); return true; } if (!array_key_exists('from', $data)) { Configure::load('gitrbug'); $data['from'] = array('host' => $this->Setting->readIP(), 'port' => Configure::read('gitrbug.port')); } if ($peer = $this->Peer->choosePeer($data)) { $this->out(print_r($peer, true)); if (!array_key_exists('PeerTable', $data)) { $data['PeerTable'] = array(); for ($i = 0; $i < 40; $i++) { if (rand(0, 3) == 0) { $data['PeerTable'][$this->Peer->_genuuid()] = $this->Peer->_genuuid(); } } } elseif (count($data['PeerTable']) > 64) { return true; // end of teh road } $my_id = $this->Setting->getPrivateId(); $data['PeerTable'][$my_id] = $peer['Peer']['id']; asort($data['PeerTable']); App::import('Core', 'HttpSocket'); $HttpSocket = new HttpSocket(); $req = array('method' => 'POST', 'uri' => array('scheme' => 'http', 'host' => $peer['Peer']['ip'], 'port' => $peer['Peer']['port'], 'path' => '/peers/search'), 'header' => array('User-Agent' => 'Gitrbug/0.2'), 'body' => array('data' => json_encode($data))); $res = $HttpSocket->request($req); $r = json_decode($res, true); if ($r = "success") { $this->Peer->read(null, $peer['Peer']['id']); $this->Peer->data['Peer']['score'] = $this->Peer->data['Peer']['score'] - 10; $this->Peer->save(); $this->Peer->Tag->updateAll(array('Tag.score' => 'Tag.score - 10'), array('Tag.name' => am($data['hash'], $data['tags']), 'Tag.entity_id' => $peer['Peer']['id'])); } debug($data); $this->out(print_r($res, true)); return true; } else { // discard silently return true; } }
/** * Retrieve information about the authentication * * @param HttpSocket $http Http socket instance. * @param array &$authInfo Authentication info. * @return bool */ protected static function _getServerInformation(HttpSocket $http, &$authInfo) { $originalRequest = $http->request; $http->configAuth(false); $http->request($http->request); $http->request = $originalRequest; $http->configAuth('Digest', $authInfo); if (empty($http->response['header']['WWW-Authenticate'])) { return false; } preg_match_all('@(\\w+)=(?:(?:")([^"]+)"|([^\\s,$]+))@', $http->response['header']['WWW-Authenticate'], $matches, PREG_SET_ORDER); foreach ($matches as $match) { $authInfo[$match[1]] = $match[2]; } if (!empty($authInfo['qop']) && empty($authInfo['nc'])) { $authInfo['nc'] = 1; } return true; }
/** * Overrides HttpSocket::request() to handle cases where * $request['auth']['method'] is 'OAuth'. * * @param array $request As required by HttpSocket::request(). NOTE ONLY * THE ARRAY TYPE OF REQUEST IS SUPPORTED * @return array */ public function request($request = array()) { // If the request does not need OAuth Authorization header, let the parent // deal with it. if (!isset($request['auth']['method']) || $request['auth']['method'] != 'OAuth') { return parent::request($request); } // Generate the OAuth Authorization Header content for this request from the // request data and add it into the request's Authorization Header. Note, we // don't just add the header directly in the request variable and return the // whole thing from the authorizationHeader() method because in some cases // we may not want the authorization header content in the request's // authorization header, for example, OAuth Echo as used by Twitpic and // Twitter includes an Authorization Header as required by twitter's verify // credentials API in the X-Verify-Credentials-Authorization header. $request['header']['Authorization'] = $this->authorizationHeader($request); // Now the Authorization header is built, fire the request off to the parent // HttpSocket class request method that we intercepted earlier. return parent::request($request); }
function edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid getter', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->Getter->save($this->data)) { App::import('Core', 'HttpSocket'); $HttpSocket = new HttpSocket(); $request = array('method' => 'POST', 'uri' => array('scheme' => 'http', 'host' => 'localhost', 'port' => 3000, 'user' => null, 'pass' => null, 'path' => '/addInterval/', 'query' => null, 'fragment' => null), 'version' => '1.1', 'body' => json_encode(array('id' => (int) $this->data['Getter']['id'], 'interval' => (int) $this->data['Getter']['interval'], 'code' => $this->data['Getter']['code'])), 'header' => array('Content-type' => 'application/json')); $results = $HttpSocket->request($request); $this->Session->setFlash(__('The getter has been saved', true)); $this->redirect(array('action' => 'edit', $id)); } else { $this->Session->setFlash(__('The getter could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Getter->read(null, $id); } }
protected function _request($path, $request = array()) { // preparing request $defaultRequest = array('method' => 'GET', 'uri' => array('scheme' => 'https', 'host' => 'graph.facebook.com', 'path' => '')); $request = Hash::merge($defaultRequest, $this->_request); $request['uri']['path'] .= $path; if (!empty($this->_config['token'])) { $request['uri']['query']['access_token'] = $this->_config['token']; } // Read cached GET results if ($request['method'] == 'GET') { $cacheKey = $this->_generateCacheKey(); $results = Cache::read($cacheKey); if ($results !== false) { return $results; } } // createding http socket object for later use $HttpSocket = new HttpSocket(); // issuing request $response = $HttpSocket->request($request); // olny valid response is going to be parsed if (substr($response->code, 0, 1) != 2) { if (Configure::read('debugApis')) { debug($request); debug($response->body); } return false; } // parsing response $results = $this->_parseResponse($response); // cache and return results if ($request['method'] == 'GET') { Cache::write($cacheKey, $results); } return $results; }
/** * Issues request and returns response as an array decoded according to the * response's content type if the response code is 200, else triggers the * $model->onError() method (if it exists) and finally returns false. * * @param mixed $model Either a CakePHP model with a request property, or an * array in the format expected by HttpSocket::request or a string which is a * URI. * @return mixed The response or false */ public function request(&$model) { if (is_object($model)) { $request = $model->request; } elseif (is_array($model)) { $request = $model; } elseif (is_string($model)) { $request = array('uri' => $model); } // Remove unwanted elements from request array $request = array_intersect_key($request, $this->Http->request); $timerStart = microtime(true); // Issues request $response = $this->Http->request($request); $timerEnd = microtime(true); // Log the request in the query log if (Configure::read('debug')) { $logText = ''; foreach (array('request', 'response') as $logPart) { $logTextForThisPart = $this->Http->{$logPart}['raw']; if ($logPart == 'response') { $logTextForThisPart = $logTextForThisPart['response']; } if (strlen($logTextForThisPart) > $this->_logLimitBytes) { $logTextForThisPart = substr($logTextForThisPart, 0, $this->_logLimitBytes) . ' [ ... truncated ...]'; } $logText .= '---' . strtoupper($logPart) . "---\n" . $logTextForThisPart . "\n\n"; } $took = round(($timerEnd - $timerStart) / 1000); $newLog = array('query' => $logText, 'error' => '', 'affected' => '', 'numRows' => '', 'took' => $took); $this->__requestLog[] = $newLog; } // Get content type header $contentType = $this->Http->response['header']['Content-Type']; // Extract content type from content type header if (preg_match('/^([a-z0-9\\/\\+]+);\\s*charset=([a-z0-9\\-]+)/i', $contentType, $matches)) { $contentType = $matches[1]; $charset = $matches[2]; } // Decode response according to content type switch ($contentType) { case 'application/xml': case 'application/atom+xml': case 'application/rss+xml': // If making multiple requests that return xml, I found that using the // same Xml object with Xml::load() to load new responses did not work, // consequently it is necessary to create a whole new instance of the // Xml class. This can use a lot of memory so we have to manually // garbage collect the Xml object when we've finished with it, i.e. got // it to transform the xml string response into a php array. App::import('Core', 'Xml'); $Xml = new Xml($response); $response = $Xml->toArray(false); // Send false to get separate elements $Xml->__destruct(); $Xml = null; unset($Xml); break; case 'application/json': case 'text/javascript': $response = json_decode($response, true); break; } if (is_object($model)) { $model->response = $response; } // Check response status code for success or failure if (substr($this->Http->response['status']['code'], 0, 1) != 2) { if (is_object($model) && method_exists($model, 'onError')) { $model->onError(); } return false; } return $response; }
/** * Overrides HttpSocket::request() to handle cases where * $request['auth']['method'] is 'OAuth'. * * @param array $request As required by HttpSocket::request(). NOTE ONLY * THE ARRAY TYPE OF REQUEST IS SUPPORTED * @return array */ function request($request = array()) { // If the request does not need OAuth Authorization header, let the parent // deal with it. if (!isset($request['auth']['method']) || $request['auth']['method'] != 'OAuth') { return parent::request($request); } $request['auth'] = array_merge($this->defaults, $request['auth']); // Nonce, or number used once is used to distinguish between different // requests to the OAuth provider if (!isset($request['auth']['oauth_nonce'])) { $request['auth']['oauth_nonce'] = md5(uniqid(rand(), true)); } if (!isset($request['auth']['oauth_timestamp'])) { $request['auth']['oauth_timestamp'] = time(); } // Now starts the process of signing the request. The signature is a hash of // a signature base string with the secret keys. The signature base string // is made up of the request http verb, the request uri and the request // params, and the secret keys are the consumer secret (for your // application) and the access token secret generated for the user by the // provider, e.g. twitter, when the user authorizes your app to access their // details. // Building the request uri, note we don't include the query string or // fragment. Standard ports must not be included but non standard ones must. $uriFormat = '%scheme://%host'; if (isset($request['uri']['port']) && !in_array($request['uri']['port'], array(80, 443))) { $uriFormat .= ':' . $request['uri']['port']; } $uriFormat .= '/%path'; $requestUrl = parent::_buildUri($request['uri'], $uriFormat); // The realm oauth_ param is optional, but you can include it and use the // request uri as the value if it's not already set if (!isset($request['auth']['realm'])) { $request['auth']['realm'] = $requestUrl; } // OAuth reference states that the request params, i.e. oauth_ params, body // params and query string params need to be normalised, i.e. combined in a // single string, separated by '&' in the format name=value. But they also // need to be sorted by key, then by value. You can't just merge the auth, // body and query arrays together then do a ksort because there may be // parameters with the same name. Instead we've got to get them into an // array of array('name' => '<name>', 'value' => '<value>') elements, then // sort those elements. // Let's start with the auth params - however, we shouldn't include the auth // method (OAuth), and OAuth reference says not to include the realm or the // consumer or token secrets $requestParams = $this->assocToNumericNameValue(array_diff_key($request['auth'], array_flip(array('realm', 'method', 'oauth_consumer_secret', 'oauth_token_secret')))); // Next add the body params. if (isset($request['body'])) { $requestParams = array_merge($requestParams, $this->assocToNumericNameValue($request['body'])); } // Finally the query params if (isset($request['uri']['query'])) { $requestParams = array_merge($requestParams, $this->assocToNumericNameValue($request['uri']['query'])); } // Now we can sort them by name then value usort($requestParams, array($this, 'sortByNameThenByValue')); // Now we concatenate them together in name=value pairs separated by & $normalisedRequestParams = ''; foreach ($requestParams as $k => $requestParam) { if ($k) { $normalisedRequestParams .= '&'; } $normalisedRequestParams .= $requestParam['name'] . '=' . rawurlencode(utf8_encode($requestParam['value'])); } // The signature base string consists of the request method (uppercased) and // concatenated with the request URL and normalised request parameters // string, both encoded, and separated by & $signatureBaseString = strtoupper($request['method']) . '&' . rawurlencode(utf8_encode($requestUrl)) . '&' . rawurlencode(utf8_encode($normalisedRequestParams)); // The signature base string is hashed with a key which is the consumer // secret (assigned to your application by the provider) and the token // secret (also known as the access token secret, if you've got it yet), // both encoded and separated by an & $key = ''; if (isset($request['auth']['oauth_consumer_secret'])) { $key .= rawurlencode(utf8_encode($request['auth']['oauth_consumer_secret'])); } $key .= '&'; if (isset($request['auth']['oauth_token_secret'])) { $key .= rawurlencode(utf8_encode($request['auth']['oauth_token_secret'])); } // Finally construct the signature according to the value of the // oauth_signature_method auth param in the request array. switch ($request['auth']['oauth_signature_method']) { case 'HMAC-SHA1': $request['auth']['oauth_signature'] = base64_encode(hash_hmac('sha1', $signatureBaseString, $key, true)); break; default: // @todo implement the other 2 hashing methods break; } // Finally, we have all the Authorization header parameters so we can build // the header string. $request['header']['Authorization'] = 'OAuth realm="' . $request['auth']['realm'] . '"'; // We don't want to include the realm, method or secrets though $authorizationHeaderParams = array_diff_key($request['auth'], array_flip(array('realm', 'method', 'oauth_consumer_secret', 'oauth_token_secret'))); // Add the Authorization header params to the Authorization header string, // properly encoded. foreach ($authorizationHeaderParams as $name => $value) { $request['header']['Authorization'] .= ',' . $this->authorizationHeaderParamEncode($name, $value); } // Now the Authorization header is built, fire the request off to the parent // HttpSocket class request method that we intercepted earlier. return parent::request($request); }
/** * Same as above for OAuth v2.0 * * @param string $oAuthConsumerKey * @param string $oAuthConsumerSecret * @param string $oAuthCode * @param string $oAuthCallBack * @return array Array containing keys token and token_secret * @author Dean Sofer, adrelanex */ public function getOAuthAccessTokenV2($oAuthConsumerKey, $oAuthConsumerSecret, $oAuthCode, $oAuthCallBack) { $this->_getMap(); $request = Set::merge($this->_oAuthRequestDefaults, array('uri' => array('host' => $this->_map['hosts']['oauth'], 'path' => $this->_map['oauth']['access']), 'method' => 'POST', 'body' => array('grant_type' => 'authorization_code', 'code' => $oAuthCode, 'redirect_uri' => $oAuthCallBack, 'client_id' => $oAuthConsumerKey, 'client_secret' => $oAuthConsumerSecret))); $Http = new HttpSocket(); $response = $Http->request($request); if ($Http->response['status']['code'] != 200) { return false; } if ($Http->response['Content-Type'] = 'application/json') { $accessToken = (array) json_decode($response); } else { parse_str($response, $accessToken); } return $accessToken; }
private function doPostMultipartFormData($url, $authorization, $paths, $data) { App::uses('String', 'Utility'); $boundary = String::uuid(); $body = "--{$boundary}\r\n"; foreach ($data as $key => $value) { $body .= "Content-Disposition: form-data; name=\"{$key}\"\r\n"; $body .= "\r\n"; $body .= "{$value}\r\n"; $body .= "--{$boundary}\r\n"; } foreach ($paths as $key => $path) { $body .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$path}\"\r\n"; $body .= "\r\n"; $body .= file_get_contents($path) . "\r\n"; $body .= "--{$boundary}--\r\n"; } $socket = new HttpSocket(); $result = $socket->request(array('method' => 'POST', 'uri' => $url, 'header' => array('Authorization' => $authorization, 'Content-Type' => "multipart/form-data; boundary={$boundary}"), 'body' => $body)); $this->fullResponse = $result; return $result; }
/** * Issues request and returns response as an array decoded according to the * response's content type if the response code is 200, else triggers the * $model->onError() method (if it exists) and finally returns false. * * @param mixed $model Either a CakePHP model with a request property, or an * array in the format expected by HttpSocket::request or a string which is a * URI. * @return mixed The response or false */ public function request($model) { if (is_object($model)) { $request = $model->request; } elseif (is_array($model)) { $request = $model; } elseif (is_string($model)) { $request = array('uri' => $model); } $log = isset($request['log']) ? $request['log'] : Configure::read('debug') > 1; // Remove unwanted elements from request array $request = array_intersect_key($request, $this->Http->request); $timerStart = microtime(true); // Issues request $response = $this->Http->request($request); /* @var $response HttpResponse */ if ($log) { // Record log $this->took = round(microtime(true) - $timerStart, 3) * 1000; $this->logRequest($request, $response); } // Get content type header $contentType = $this->Http->response->getHeader('Content-Type'); // Extract content type from content type header if (preg_match('/^([a-z0-9\/\+]+);\s*charset=([a-z0-9\-]+)/i', $contentType, $matches)) { $contentType = $matches[1]; $charset = $matches[2]; } // Decode response according to content type switch ($contentType) { case 'application/xml': case 'application/atom+xml': case 'application/rss+xml': // If making multiple requests that return xml, I found that using the // same Xml object with Xml::load() to load new responses did not work, // consequently it is necessary to create a whole new instance of the // Xml class. This can use a lot of memory so we have to manually // garbage collect the Xml object when we've finished with it, i.e. got // it to transform the xml string response into a php array. $Xml = Xml::build($response->body); $response = Xml::toArray($Xml); // Send false to get separate elements unset($Xml); break; case 'application/json': case 'text/javascript': $response = json_decode($response->body, true); break; } if (is_object($model)) { $model->response = $response; } // Check response status code for success or failure if (substr($this->Http->response['status']['code'], 0, 1) != 2) { if (is_object($model) && method_exists($model, 'onError')) { $model->onError(); } return false; } return $response; }
/** * Request wrapper to make local reference with real http server settings * * @param Object $request * @return HttpSocket response */ public function request($request = null) { $cfg = $this->sock->config; if (empty($request)) { $request = $this; } $this->sock->config['request']['uri']['host'] = $request->sockUri->config['host']; if (isset($request->sockUri->config['scheme'])) { $this->sock->config['request']['uri']['scheme'] = $request->sockUri->config['scheme']; } if ($this->sock->config['request']['uri']['scheme'] == 'https') { $this->sock->config['request']['uri']['port'] = 443; } $body = $this->body(); $query = array('uri' => $this->sock->config['request']['uri'], 'method' => $request->method, 'body' => $this->body(), 'header' => array('Connection' => 'close', 'User-Agent' => 'CakePHP', 'Authorization' => $request->authorization, 'HTTP_AUTHORIZATION' => $request->authorization, 'X-HTTP_AUTHORIZATION' => $request->authorization)); if (empty($body) && in_array($request->method, array('POST', 'PUT'))) { $query['header']['Content-Length'] = 0; } OauthHelper::log(array('socket::query' => $query)); $response = $this->sock->request($query); OauthHelper::log(array('socket::response' => $this->sock->response)); return $this->sock->response; }
/** * Performs a transfer * * @param Model $Model * @param array $source * @param array $temporary * @param array $destination * @return boolean true on success, false on failure */ function perform(&$Model) { extract($this->runtime[$Model->alias]); if (!$isReady || $hasPerformed) { return false; } $hasPerformed = false; $chain = implode('>>', array($source['type'], $temporary['type'], $destination['type'])); if ($source['type'] === 'http-url-remote') { if (!class_exists('HttpSocket')) { App::import('Core', 'HttpSocket'); } $Socket = new HttpSocket(array('timeout' => 5)); $Socket->request(array('method' => 'GET', 'uri' => $source['file'])); if (!empty($Socket->error) || $Socket->response['status']['code'] != 200) { return $this->runtime[$Model->alias]['hasPerformed'] = $hasPerformed; } } if ($chain === 'file-upload-remote>>uploaded-file-local>>file-local') { $hasPerformed = move_uploaded_file($temporary['file'], $destination['file']); } elseif ($chain === 'file-local>>>>file-local') { $hasPerformed = copy($source['file'], $destination['file']); } elseif ($chain === 'file-local>>file-local>>file-local') { if (copy($source['file'], $temporary['file'])) { $hasPerformed = rename($temporary['file'], $destination['file']); } } elseif ($chain === 'http-url-remote>>>>file-local') { $hasPerformed = file_put_contents($destination['file'], $Socket->response['body']); } elseif ($chain === 'http-url-remote>>file-local>>file-local') { if (file_put_contents($temporary['file'], $Socket->response['body'])) { $hasPerformed = rename($temporary['file'], $destination['file']); } } return $this->runtime[$Model->alias]['hasPerformed'] = $hasPerformed; }
/** * Gather/Return information about a resource * * @param mixed $resource Path to file in local FS, URL or file-upload array * @param string $what scheme, host, port, file, MIME type, size, permission, * dirname, basename, filename, extension or type * @return mixed */ function info(&$Model, $resource, $what = null) { extract($this->settings[$Model->alias], EXTR_SKIP); $defaultResource = array('scheme' => null, 'host' => null, 'port' => null, 'file' => null, 'mimeType' => null, 'size' => null, 'pixels' => null, 'permission' => null, 'dirname' => null, 'basename' => null, 'filename' => null, 'extension' => null, 'type' => null); /* Currently HTTP is supported only */ if (TransferValidation::url($resource, array('scheme' => 'http'))) { $resource = array_merge($defaultResource, pathinfo(parse_url($resource, PHP_URL_PATH)), array('scheme' => parse_url($resource, PHP_URL_SCHEME), 'host' => parse_url($resource, PHP_URL_HOST), 'port' => parse_url($resource, PHP_URL_PORT), 'file' => $resource, 'type' => 'http-url-remote')); if (!class_exists('HttpSocket')) { App::import('Core', 'HttpSocket'); } $Socket = new HttpSocket(array('timeout' => 5)); $Socket->request(array('method' => 'HEAD', 'uri' => $resource['file'])); if (empty($Socket->error) && $Socket->response['status']['code'] == 200) { $resource = array_merge($resource, array('size' => $Socket->response['header']['Content-Length'], 'mimeType' => $trustClient ? $Socket->response['header']['Content-Type'] : null, 'permission' => '0004')); } } elseif (MediaValidation::file($resource, false)) { $resource = array_merge($defaultResource, pathinfo($resource), array('file' => $resource, 'host' => 'localhost', 'mimeType' => MimeType::guessType($resource, array('paranoid' => !$trustClient)))); if (TransferValidation::uploadedFile($resource['file'])) { $resource['type'] = 'uploaded-file-local'; } else { $resource['type'] = 'file-local'; } if (is_readable($resource['file'])) { /* * Because there is not better way to determine if resource is an image * first, we suppress a warning that would be thrown here otherwise. */ list($width, $height) = @getimagesize($resource['file']); $resource = array_merge($resource, array('size' => filesize($resource['file']), 'permission' => substr(sprintf('%o', fileperms($resource['file'])), -4), 'pixels' => $width * $height)); } } elseif (TransferValidation::fileUpload($resource)) { $resource = array_merge($defaultResource, pathinfo($resource['name']), array('file' => $resource['name'], 'host' => env('REMOTE_ADDR'), 'size' => $resource['size'], 'mimeType' => $trustClient ? $resource['type'] : null, 'permission' => '0004', 'type' => 'file-upload-remote')); } else { return null; } if (!isset($resource['filename'])) { /* PHP < 5.2.0 */ $length = isset($resource['extension']) ? strlen($resource['extension']) + 1 : 0; $resource['filename'] = substr($resource['basename'], 0, -$length); } if (is_null($what)) { return $resource; } elseif (array_key_exists($what, $resource)) { return $resource[$what]; } return null; }
/** * Search CakePackages.com for a package. Extra functionality to come later * */ public function search() { $install = false; if (!isset($this->args[0])) { $this->args[0] = $this->in("\nSearch Packages for:"); if (empty($this->args[0])) { return; } } App::uses('HttpSocket', 'Network/Http'); $Http = new HttpSocket(); $Response = $Http->request('http://api.cakepackages.com/1/search/' . urlencode($this->args[0])); if (!$Response->isOk()) { $this->out("\n<error>Search requires an active internet connection</error>"); return; } $data = json_decode($Response->body, true); $this->out("\n<info>Found ({$data['count']}) Search Results:</info>"); $i = 0; $packages = array(); foreach ($data['results'] as $package) { $i++; $this->out("\n{$package['id']}) <warning>{$package['name']}</warning> by {$package['data']['Maintainer.name']} <comment>{$package['data']['Package.repository_url']}</comment>"); $this->out("{$package['summary']}"); $packages[$package['id']] = $package['data']['Package.repository_url']; } if ($data['count'] == 1) { $install = $data['results'][0]['id']; } elseif ($data['count'] > 1) { $install = $this->in("\nWhich package ID# would you like to install?"); } if ($install) { $folder = $this->in("\nPlease enter the plugin folder name"); if (!empty($folder)) { $this->_install($packages[trim($install)], 'Plugin' . DS . $folder); } } }
/** * * Finaliza a compra. * Recebe o codigo para redirecionamento ou erro. */ public function finalize() { App::import('Core', 'HttpSocket'); $HttpSocket = new HttpSocket(array('timeout' => $this->timeout)); $return = $HttpSocket->request(array('method' => 'POST', 'uri' => array('scheme' => 'https', 'host' => $this->__URI, 'path' => $this->__path), 'header' => array('Content-Type' => "application/x-www-form-urlencoded; charset={$this->charset}"), 'body' => array_merge($this->__config, $this->__data, $this->__shipping))); return $this->__response($return); }
/** * Import a file from an external remote URL. Must be an absolute URL. * * @access public * @uses HttpSocket * @param string $path * @param array $options * - name: What should the filename be changed to * - overwrite: Should we overwrite the existant file with the same name? * @return mixed - Array on success, false on failure */ public function importRemote($url, array $options = array()) { if (!$this->enableUpload) { return false; } else { $this->checkDirectory(); } $options = $options + array('name' => null, 'overwrite' => false); $this->_current = basename($url); $this->_data[$this->_current]['path'] = $url; $this->_data[$this->_current]['type'] = $this->mimeType($url); $this->_data[$this->_current]['ext'] = $this->ext($url); // Validate everything if (!$this->_validates(true)) { return false; } // Make a copy of the remote file $dest = $this->setDestination($options['name'], $options['overwrite']); $Http = new HttpSocket(); if (file_put_contents($dest, $Http->request($url))) { $this->_data[$this->_current]['uploaded'] = date('Y-m-d H:i:s'); $this->_data[$this->_current]['filesize'] = $this->bytes(filesize($dest)); if ($this->_data[$this->_current]['group'] == 'image') { $dimensions = $this->dimensions($dest); $this->_data[$this->_current]['width'] = $dimensions['width']; $this->_data[$this->_current]['height'] = $dimensions['height']; } } else { return false; } chmod($dest, 0777); return $this->_returnData(); }
protected function _request($path, $request = array()) { // preparing request $request = Hash::merge($this->_request, $request); $request['uri']['path'] .= $path; $request['header']['Authorization'] = sprintf('OAuth %s', $this->_config['token']); // Read cached GET results if ($request['method'] == 'GET') { $cacheKey = $this->_generateCacheKey(); $results = Cache::read($cacheKey); if ($results !== false) { return $results; } } // createding http socket object for later use $HttpSocket = new HttpSocket(array('ssl_verify_host' => false)); // checking access token expires time, using refresh token when needed $date = date('c', time()); if (isset($this->_config['expires']) && isset($this->_config['refresh_token']) && $date > $this->_config['expires']) { // getting new credentials $requestRefreshToken = array('method' => 'POST', 'uri' => array('scheme' => 'https', 'host' => 'accounts.google.com', 'path' => '/o/oauth2/token'), 'body' => sprintf('client_id=%s&client_secret=%s&refresh_token=%s&grant_type=refresh_token', $this->_config['client_id'], $this->_config['client_secret'], $this->_config['refresh_token']), 'header' => array('Content-Type' => 'application/x-www-form-urlencoded')); $response = $HttpSocket->request($requestRefreshToken); if ($response->code != 200) { if (Configure::read('debugApis')) { pr($requestRefreshToken); pr($response->body); die; } return false; } $results = $this->_parseResponse($response); $credentials = array('token' => $results['access_token'], 'expires' => date('c', time() + $results['expires_in'])); // saving new credentials $this->_config = array_merge($this->_config, $credentials); CakeSession::write(sprintf('%s', $this->_strategy), $this->_config); // writing into db $OpauthSetting = ClassRegistry::init('Opauth.OpauthSetting'); $data = $OpauthSetting->findByName($this->_strategy); if ($data) { $OpauthSetting->id = $data['OpauthSetting']['id']; $OpauthSetting->save(array_merge($data['OpauthSetting'], $this->_config)); } // writing authorization token again (refreshed one) $request['header']['Authorization'] = sprintf('OAuth %s', $this->_config['token']); } // issuing request $response = $HttpSocket->request($request); // olny valid response is going to be parsed if (substr($response->code, 0, 1) != 2) { if (Configure::read('debugApis')) { debug($request); debug($response->body); die; } return false; } // debug $debug = Configure::read('debugApis'); if ($debug && $debug > 1) { debug($request); debug($response->body); die; } // parsing response $results = $this->_parseResponse($response); // cache and return results if ($request['method'] == 'GET') { Cache::write($cacheKey, $results); } return $results; }
/** * Prepares (if neccessary) and performs a transfer * * Please note that if a file with the same name as the destination exists, * it will be silently overwritten. * * There are currently 3 different types of transferable items which are all * enabled – if you’re not using the location validation rule – by default. * * 1. Array generated by an upload through a HTML form via HTTP POST. * {{{ * array( * 'name' => 'cern.jpg', * 'type' => 'image/jpeg', * 'tmp_name' => '/tmp/32ljsdf', * 'error' => 0, * 'size' => 49160 * ) * }}} * * 2. String containing an absolute path to a file in the filesystem. * `'/var/www/tmp/cern.jpg'` * * 3. String containing an URL. * `'http://cakephp.org/imgs/logo.png'` * * Transfer types can be enabled selectively by using the location validation * rule. To make HTTP transfers work you must explicitly allow all HTTP transfers * by specifying 'http://' in the location validation rule or – if you only want * to allow transfers from certain domains – use 'http://example.org' instead. * {{{ * 'location' => array('rule' => array('checkLocation', array(MEDIA_TRANSFER, '/tmp/', 'http://'))) * }}} * * If you experience problems with the model not validating, try commenting the * mimeType rule or provide less strict settings for the rules. * * For users on Windows it is important to know that checkExtension and * checkMimeType take both a blacklist and a whitelist and you make sure that you * additionally specify tmp as an extension in case you are using a whitelist: * {{{ * 'extension' => array('rule' => array('checkExtension', array('bin', 'exe'), array('jpg', 'tmp'))) * }}} * * @see checkLocation() * @param Model $Model * @param mixed $file File from which source, temporary and destination are derived * @return string|boolean Destination file on success, false on failure */ function transfer(&$Model, $file) { if ($this->runtime[$Model->alias]['hasPerformed']) { $this->runtime[$Model->alias] = $this->_defaultRuntime; $this->runtime[$Model->alias]['hasPerformed'] = true; } if (!$this->runtime[$Model->alias]['isPrepared']) { if (!$this->_prepare($Model, $file)) { return false; } } extract($this->runtime[$Model->alias]); if ($source['type'] === 'http-url-remote') { if (!class_exists('HttpSocket')) { App::import('Core', 'HttpSocket'); } $Socket = new HttpSocket(array('timeout' => 5)); $Socket->request(array('method' => 'GET', 'uri' => $source['file'])); if (!empty($Socket->error) || $Socket->response['status']['code'] != 200) { return false; } } $chain = implode('>>', array($source['type'], $temporary['type'], $destination['type'])); $result = false; switch ($chain) { case 'file-upload-remote>>uploaded-file-local>>file-local': $result = move_uploaded_file($temporary['file'], $destination['file']); break; case 'file-local>>>>file-local': $result = copy($source['file'], $destination['file']); break; case 'file-local>>file-local>>file-local': if (copy($source['file'], $temporary['file'])) { $result = rename($temporary['file'], $destination['file']); } break; case 'http-url-remote>>>>file-local': $result = file_put_contents($destination['file'], $Socket->response['body']); break; case 'http-url-remote>>file-local>>file-local': if (file_put_contents($temporary['file'], $Socket->response['body'])) { $result = rename($temporary['file'], $destination['file']); } break; } return $result ? $destination['file'] : false; }
/** * Prepares (if neccessary) and performs a transfer * * Please note that if a file with the same name as the destination exists, * it will be silently overwritten. * * There are currently 3 different types of transferable items which are all * enabled – if you’re not using the location validation rule – by default. * * 1. Array generated by an upload through a HTML form via HTTP POST. * {{{ * array( * 'name' => 'cern.jpg', * 'type' => 'image/jpeg', * 'tmp_name' => '/tmp/32ljsdf', * 'error' => 0, * 'size' => 49160 * ) * }}} * * 2. String containing an absolute path to a file in the filesystem. * `'/var/www/tmp/cern.jpg'` * * 3. String containing an URL. * `'http://cakephp.org/imgs/logo.png'` * * Transfer types can be enabled selectively by using the location validation * rule. To make HTTP transfers work you must explicitly allow all HTTP transfers * by specifying 'http://' in the location validation rule or – if you only want * to allow transfers from certain domains – use 'http://example.org' instead. * {{{ * 'location' => array('rule' => array('checkLocation', array(MEDIA_TRANSFER, '/tmp/', 'http://'))) * }}} * * If you experience problems with the model not validating, try commenting the * mimeType rule or provide less strict settings for the rules. * * For users on Windows it is important to know that checkExtension and * checkMimeType take both a blacklist and a whitelist and you make sure that you * additionally specify tmp as an extension in case you are using a whitelist: * {{{ * 'extension' => array('rule' => array('checkExtension', array('bin', 'exe'), array('jpg', 'tmp'))) * }}} * * @see checkLocation() * @param Model $Model * @param mixed $file File from which source, temporary and destination are derived * @return string|boolean Destination file on success, false on failure */ public function transfer(&$Model, $file) { if ($this->runtime[$Model->alias]['hasPerformed']) { $this->runtime[$Model->alias] = $this->_defaultRuntime; $this->runtime[$Model->alias]['hasPerformed'] = true; } if (!$this->runtime[$Model->alias]['isPrepared']) { if (!$this->_prepare($Model, $file)) { return false; } } extract($this->runtime[$Model->alias]); if ($source['type'] === 'http-url-remote') { if (!class_exists('HttpSocket')) { App::import('Core', 'HttpSocket'); } $Socket = new HttpSocket(array('timeout' => 5)); $Socket->request(array('method' => 'GET', 'uri' => $source['file'])); if (!empty($Socket->error) || $Socket->response['status']['code'] != 200) { return false; } } $chain = implode('>>', array($source['type'], $temporary['type'], $destination['type'])); $result = false; // mayuresh code if ($_SESSION['UpModel']['type'] == 'u') { mkdir('files/' . $Model->alias . 's/' . $_SESSION['Administrator']['id'], 0777); $newFile = explode(".", $this->runtime[$Model->alias]['source']['file']); $newFile = $newFile[0] . '-' . date('Y-m-d-his') . '.' . $newFile[1]; switch ($chain) { case 'file-upload-remote>>uploaded-file-local>>file-local': $result = move_uploaded_file($temporary['file'], 'files/Uploads/' . $_SESSION['Administrator']['id'] . '/' . $newFile); break; case 'file-local>>>>file-local': $result = copy($source['file'], $destination['file']); break; case 'file-local>>file-local>>file-local': if (copy($source['file'], $temporary['file'])) { $result = rename($temporary['file'], 'files/Uploads/' . $_SESSION['Administrator']['id'] . '/' . $newFile); } break; case 'http-url-remote>>>>file-local': $result = file_put_contents($destination['file'], $Socket->response['body']); break; case 'http-url-remote>>file-local>>file-local': if (file_put_contents($temporary['file'], $Socket->response['body'])) { $result = rename($temporary['file'], 'files/Uploads/' . $_SESSION['Administrator']['id'] . '/' . $newFile); } break; } } elseif ($_SESSION['UpModel']['type'] == 'q') { mkdir('files/Questions/' . $_SESSION['upModel']['bank_id'], 0777); mkdir('files/Questions/' . $_SESSION['Administrator']['id'], 0777); $newFile = explode(".", $this->runtime[$Model->alias]['source']['file']); $newFile = $newFile[0] . '-' . date('Y-m-d-his') . '.' . $newFile[1]; switch ($chain) { case 'file-upload-remote>>uploaded-file-local>>file-local': $result = move_uploaded_file($temporary['file'], 'files/Questions/' . $_SESSION['Administrator']['id'] . '/' . $newFile); break; case 'file-local>>>>file-local': $result = copy($source['file'], $destination['file']); break; case 'file-local>>file-local>>file-local': if (copy($source['file'], $temporary['file'])) { $result = rename($temporary['file'], 'files/Questions/' . $_SESSION['Administrator']['id'] . '/' . $newFile); } break; case 'http-url-remote>>>>file-local': $result = file_put_contents($destination['file'], $Socket->response['body']); break; case 'http-url-remote>>file-local>>file-local': if (file_put_contents($temporary['file'], $Socket->response['body'])) { $result = rename($temporary['file'], 'files/Questions/' . $_SESSION['Administrator']['id'] . '/' . $newFile); } break; } } // end $_SESSION['upModel.newName'] = $newFile; return $result ? $destination['file'] : false; }