public function makeHttpResponseFor($nativeVars) { $response = $this->getServerResponseFor($nativeVars); return HttpResponse::fromString($response); }
/** * Make http request to zotero api * * @param string $url target api url * @param string $method http method GET|POST|PUT|DELETE * @param string $body request body if write * @param array $headers headers to set on request * @return HTTP_Response */ public function request($url, $method = "GET", $body = NULL, $headers = array(), $basicauth = array()) { if (is_array($url)) { $url = Url::apiRequestString($url); } libZoteroDebug("url being requested: " . $url . "\n\n"); $ch = curl_init(); $httpHeaders = array(); //set api version - allowed to be overridden by passed in value if (!isset($headers['Zotero-API-Version'])) { $headers['Zotero-API-Version'] = ZOTERO_API_VERSION; } if (!isset($headers['User-Agent'])) { $headers['User-Agent'] = 'LibZotero-php'; } foreach ($headers as $key => $val) { $httpHeaders[] = "{$key}: {$val}"; } //disable Expect header $httpHeaders[] = 'Expect:'; if (!empty($basicauth)) { $passString = $basicauth['username'] . ':' . $basicauth['password']; curl_setopt($ch, CURLOPT_USERPWD, $passString); curl_setopt($ch, CURLOPT_FORBID_REUSE, true); } else { curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders); curl_setopt($ch, CURLOPT_MAXREDIRS, 3); if ($this->followRedirects) { curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); } else { curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); } $umethod = strtoupper($method); switch ($umethod) { case "GET": curl_setopt($ch, CURLOPT_HTTPGET, true); break; case "POST": curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); break; case "PUT": curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); break; case "DELETE": curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); break; } $gotCached = false; if ($this->cacheResponses && $umethod == 'GET') { $cachedResponse = $this->cache->fetch($url, $success); if ($success) { $responseBody = $cachedResponse['responseBody']; $responseInfo = $cachedResponse['responseInfo']; $zresponse = HttpResponse::fromString($responseBody); $gotCached = true; } } if (!$gotCached) { $responseBody = curl_exec($ch); $responseInfo = curl_getinfo($ch); $zresponse = HttpResponse::fromString($responseBody); //Zend Response does not parse out the multiple sets of headers returned when curl automatically follows //a redirect and the new headers are left in the body. Zend_Http_Client gets around this by manually //handling redirects. That may end up being a better solution, but for now we'll just re-read responses //until a non-redirect is read if ($this->followRedirects) { while ($zresponse->isRedirect()) { $redirectedBody = $zresponse->getBody(); $zresponse = HttpResponse::fromString($redirectedBody); } } $saveCached = array('responseBody' => $responseBody, 'responseInfo' => $responseInfo); if ($this->cacheResponses && !$zresponse->isError()) { $this->cache->store($url, $saveCached, $this->cachettl); } } $this->_lastResponse = $zresponse; return $zresponse; }
/** * To perform chnage set requests in non-batch mode. For any update operation * on an entity (not binding) this function will use MERGE if $replaceOnUpdateOption * is false else PUT. * * @param boolean $replaceOnUpdateOption * @return DataServiceResponse */ public function NonBatchRequest($replaceOnUpdateOption) { $headers = array(); $code = null; do { $headers = array(); $code = null; try { $httpRequest = $this->CreateRequestHeaderForSingleChange($replaceOnUpdateOption); if ($httpRequest != null || $this->_entryIndex < count($this->_changedEntries)) { $contentStream = $this->CreateRequestBodyForSingleChange($this->_entryIndex); if ($contentStream != null && ($stream = $contentStream->getStream()) != null) { $httpMethod = $httpRequest->getMethod(); if ($contentStream->IsKnownMemoryStream() && $httpMethod == HttpVerb::POST) { //$httpRequest->ApplyHeaders(array(HttpRequestHeader::ContentLength => strlen($stream))); } if ($httpMethod == HttpVerb::POST || $httpMethod == HttpVerb::MERGE) { $httpRequest->setPostBody($stream); } else { if ($httpMethod == HttpVerb::PUT) { $httpRequest->setPutBody($stream); } } } $this->_context->OnBeforeRequestInternal($httpRequest); //HttpRequest::GetResponse can throw InvalidOperation exception //if the curl_exec fails (ex: could not connect to host) //the below catch blcok will catch that exception and //re-throw it as ODataServiceExcpetion. $httpRawResponse = $httpRequest->GetResponse(); $httpResponse = HttpResponse::fromString($httpRawResponse); $this->_context->OnAfterResponseInternal($httpResponse); if ($httpResponse->isError()) { $headers = $httpResponse->getHeaders(); $code = $httpResponse->getCode(); $httpException = $this->getHttpException($httpResponse); throw new InvalidOperation($httpException); } $httpCode = $httpResponse->getCode(); $this->UpdateChangeOrderIDToHttpStatus($httpCode); $this->_operationResponses[] = new OperationResponse($httpResponse->getHeaders(), '', $httpCode); $this->HandleOperationResponse($httpResponse); } else { $this->_completed = true; $this->EndNonBatchRequest(); } } catch (InvalidOperation $exception) { $this->EndNonBatchRequest(); throw new ODataServiceException($exception->getError() . $exception->getDetailedError(), '', $headers, $code); } } while (!$this->_completed); return new DataServiceResponse(array(), '', $this->_operationResponses, false); }
/** * Execute a Http request and returns the Http Response. If any error happens * then the $isError flag will be set to true and $innerException will * contain the exception string. From the returned http response object more * details (http headers, code, message and body) can be retrieved. * [Note: Do not call this function from your application, it is used internally] * * @param HttpRequest $httpRequest * @param string $dataServiceVersion * @param boolean [out] $isError * @param string [out] $innerException * @return HttpResponse */ public function ExecuteAndReturnResponse($httpRequest, $dataServiceVersion, &$isError, &$innerException) { $this->OnBeforeRequestInternal($httpRequest); $httpRawResponse = ''; //need a try catch, because during curl_exec, if curl failed to //connet to the OData Service it will throw InvalidOperation //exception try { $httpRawResponse = $httpRequest->GetResponse(); } catch (InvalidOperation $exception) { $isError = true; $innerException = $exception->getError() . $exception->getDetailedError(); return new Microsoft_Http_Response('404', array()); } $httpResponse = HttpResponse::fromString($httpRawResponse); $this->OnAfterResponseInternal($httpResponse); $isError = $httpResponse->IsError(); $headers = $httpResponse->getHeaders(); if ($isError) { if (isset($headers[HttpRequestHeader::ContentType])) { if (strpos(strtolower($headers[HttpRequestHeader::ContentType]), strtolower(Resource::Content_Type_ATOM)) !== FALSE) { $innerException = $httpResponse->getMessage(); } else { $outerError = $innerError = null; /*The error string can be in the format: retrive the error <?xml version="1.0" encoding="utf-8" standalone="yes"?> <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> <code></code> <message xml:lang="en-US">The error</message> </error>*/ AtomParser::GetErrorDetails($httpResponse->getBody(), $outerError, $innerError); $innerException = $outerError . "<br/>" . $innerError; } } else { $innerException = $httpResponse->getMessage(); } } if (isset($headers['Dataserviceversion']) && (int) $headers['Dataserviceversion'] > (int) $dataServiceVersion) { $isError = true; $innerException = Resource::VersionMisMatch . $headers['Dataserviceversion']; } return $httpResponse; }
/** * To get toekn from ACS. * * @return <string> * @throws ACSUtilException */ public function GetACSToken() { $postBody = 'wrap_name' . '=' . urlencode($this->_wrap_name) . '&' . 'wrap_password' . '=' . urlencode($this->_wrap_password) . '&' . 'wrap_scope' . '=' . $this->_wrap_scope; foreach ($this->_claims as $key => $value) { $postBody = $postBody . '&' . $key . '=' . $value; } $url = 'https://' . $this->_service_namespace . '.' . 'accesscontrol.windows.net' . '/' . 'WRAPv0.9'; $httpRequest = new HttpRequest(HttpVerb::POST, $url, null, $this->_proxy, array(), $postBody, false); $httpRawResponse = null; try { $httpRawResponse = $httpRequest->GetResponse(); } catch (InvalidOperation $exception) { throw new ACSUtilException($exception->getError(), array(), null); } $httpResponse = HttpResponse::fromString($httpRawResponse); if ($httpResponse->isError()) { throw new ACSUtilException($httpResponse->getMessage() . '<br/>' . $httpResponse->getBody(), $httpResponse->getHeaders(), $httpResponse->getCode()); } $this->_token = $httpResponse->getBody(); if (strpos($this->_token, 'Error') !== false) { throw new ACSUtilException('Invalid Token received:' . $this->_token, array(), null); } $params = explode('&', $this->_token); if (isset($params[0]) && strpos($params[0], 'wrap_access_token') === 0) { $parts = explode('=', $params[0]); $this->_token = $parts[1]; } else { throw new ACSUtilException('Invalid Token received:' . $this->token, array(), null); } return $this->_token; }
/** * To retrive the service metadata using Curl. * * @return string */ protected function _getMetaDataOverCurl() { $curlHandle = curl_init(); curl_setopt($curlHandle, CURLOPT_URL, $this->_options['/uri_withoutSlash'] . '/' . '$metadata'); curl_setopt($curlHandle, CURLOPT_HEADER, true); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, false); if (isset($this->_options['/auth'])) { switch ($this->_options['/auth']) { case 'windows': curl_setopt($curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($curlHandle, CURLOPT_USERPWD, $this->_options['/u'] . ":" . $this->_options['/p']); break; case 'acs': try { $proxy = null; if (isset($this->_options['/ph'])) { $proxy = new HttpProxy($this->_options['/ph'], $this->_options['/pp'], $this->_options['/pu'], $this->_options['/ppwd']); } $acsutil = new ACSUtil($this->_options['/sn'], $this->_options['/u'], $this->_options['/p'], $this->_options['/at'], array(), $proxy); $token = $acsutil->GetACSToken(); $authHeaderValue = 'WRAP access_token="' . urldecode($token) . '"'; curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array('authorization: ' . $authHeaderValue)); } catch (ACSUtilException $exception) { $error = str_replace("<br/>", "\n", $exception->getError()); throw new Exception($error); } break; } } if (isset($this->_options['/ph']) && $this->_options['/ups'] == 'yes') { curl_setopt($curlHandle, CURLOPT_PROXY, $this->_options['/ph'] . ":" . $this->_options['/pp']); if (isset($this->_options['/pu'])) { curl_setopt($curlHandle, CURLOPT_PROXYUSERPWD, $this->_options['/pu'] . ":" . $this->_options['/ppwd']); curl_setopt($curlHandle, CURLOPT_HTTPPROXYTUNNEL, 1); } } $httpRawResponse = curl_exec($curlHandle); if (!$httpRawResponse) { throw new Exception(self::$_messages['Request_Error'] . curl_error($curlHandle)); } $httpResponse = HttpResponse::fromString($httpRawResponse); if ($httpResponse->isError()) { $exception = 'Message:' . $httpResponse->getMessage(); $exception .= "\n\n"; $exception .= $httpResponse->getBody(); throw new Exception($exception); } return $httpResponse->getBody(); }