PageRenderTime 38ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/lib/google/io/Google_CurlIO.php

https://gitlab.com/x33n/platform
PHP | 278 lines | 160 code | 33 blank | 85 comment | 34 complexity | 631378f98a0a1c694c904f3014c53959 MD5 | raw file
  1. <?php
  2. /*
  3. * Copyright 2010 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /**
  18. * Curl based implementation of apiIO.
  19. *
  20. * @author Chris Chabot <chabotc@google.com>
  21. * @author Chirag Shah <chirags@google.com>
  22. */
  23. require_once 'Google_CacheParser.php';
  24. class Google_CurlIO implements Google_IO {
  25. const CONNECTION_ESTABLISHED = "HTTP/1.0 200 Connection established\r\n\r\n";
  26. const FORM_URLENCODED = 'application/x-www-form-urlencoded';
  27. private static $ENTITY_HTTP_METHODS = array("POST" => null, "PUT" => null);
  28. private static $HOP_BY_HOP = array(
  29. 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
  30. 'te', 'trailers', 'transfer-encoding', 'upgrade');
  31. private $curlParams = array (
  32. CURLOPT_RETURNTRANSFER => true,
  33. CURLOPT_FOLLOWLOCATION => 0,
  34. CURLOPT_FAILONERROR => false,
  35. CURLOPT_SSL_VERIFYPEER => true,
  36. CURLOPT_HEADER => true,
  37. CURLOPT_VERBOSE => false,
  38. );
  39. /**
  40. * Perform an authenticated / signed apiHttpRequest.
  41. * This function takes the apiHttpRequest, calls apiAuth->sign on it
  42. * (which can modify the request in what ever way fits the auth mechanism)
  43. * and then calls apiCurlIO::makeRequest on the signed request
  44. *
  45. * @param Google_HttpRequest $request
  46. * @return Google_HttpRequest The resulting HTTP response including the
  47. * responseHttpCode, responseHeaders and responseBody.
  48. */
  49. public function authenticatedRequest(Google_HttpRequest $request) {
  50. $request = Google_Client::$auth->sign($request);
  51. return $this->makeRequest($request);
  52. }
  53. /**
  54. * Execute a apiHttpRequest
  55. *
  56. * @param Google_HttpRequest $request the http request to be executed
  57. * @return Google_HttpRequest http request with the response http code, response
  58. * headers and response body filled in
  59. * @throws Google_IOException on curl or IO error
  60. */
  61. public function makeRequest(Google_HttpRequest $request) {
  62. // First, check to see if we have a valid cached version.
  63. $cached = $this->getCachedRequest($request);
  64. if ($cached !== false) {
  65. if (Google_CacheParser::mustRevalidate($cached)) {
  66. $addHeaders = array();
  67. if ($cached->getResponseHeader('etag')) {
  68. // [13.3.4] If an entity tag has been provided by the origin server,
  69. // we must use that entity tag in any cache-conditional request.
  70. $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
  71. } elseif ($cached->getResponseHeader('date')) {
  72. $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
  73. }
  74. $request->setRequestHeaders($addHeaders);
  75. } else {
  76. // No need to revalidate the request, return it directly
  77. return $cached;
  78. }
  79. }
  80. if (array_key_exists($request->getRequestMethod(),
  81. self::$ENTITY_HTTP_METHODS)) {
  82. $request = $this->processEntityRequest($request);
  83. }
  84. $ch = curl_init();
  85. curl_setopt_array($ch, $this->curlParams);
  86. curl_setopt($ch, CURLOPT_URL, $request->getUrl());
  87. if ($request->getPostBody()) {
  88. curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPostBody());
  89. }
  90. $requestHeaders = $request->getRequestHeaders();
  91. if ($requestHeaders && is_array($requestHeaders)) {
  92. $parsed = array();
  93. foreach ($requestHeaders as $k => $v) {
  94. $parsed[] = "$k: $v";
  95. }
  96. curl_setopt($ch, CURLOPT_HTTPHEADER, $parsed);
  97. }
  98. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
  99. curl_setopt($ch, CURLOPT_USERAGENT, $request->getUserAgent());
  100. $respData = curl_exec($ch);
  101. // Retry if certificates are missing.
  102. if (curl_errno($ch) == CURLE_SSL_CACERT) {
  103. error_log('SSL certificate problem, verify that the CA cert is OK.'
  104. . ' Retrying with the CA cert bundle from google-api-php-client.');
  105. curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
  106. $respData = curl_exec($ch);
  107. }
  108. $respHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  109. $respHttpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
  110. $curlErrorNum = curl_errno($ch);
  111. $curlError = curl_error($ch);
  112. curl_close($ch);
  113. if ($curlErrorNum != CURLE_OK) {
  114. throw new Google_IOException("HTTP Error: ($respHttpCode) $curlError");
  115. }
  116. // Parse out the raw response into usable bits
  117. list($responseHeaders, $responseBody) =
  118. self::parseHttpResponse($respData, $respHeaderSize);
  119. if ($respHttpCode == 304 && $cached) {
  120. // If the server responded NOT_MODIFIED, return the cached request.
  121. if (isset($responseHeaders['connection'])) {
  122. $hopByHop = array_merge(
  123. self::$HOP_BY_HOP,
  124. explode(',', $responseHeaders['connection'])
  125. );
  126. $endToEnd = array();
  127. foreach($hopByHop as $key) {
  128. if (isset($responseHeaders[$key])) {
  129. $endToEnd[$key] = $responseHeaders[$key];
  130. }
  131. }
  132. $cached->setResponseHeaders($endToEnd);
  133. }
  134. return $cached;
  135. }
  136. // Fill in the apiHttpRequest with the response values
  137. $request->setResponseHttpCode($respHttpCode);
  138. $request->setResponseHeaders($responseHeaders);
  139. $request->setResponseBody($responseBody);
  140. // Store the request in cache (the function checks to see if the request
  141. // can actually be cached)
  142. $this->setCachedRequest($request);
  143. // And finally return it
  144. return $request;
  145. }
  146. /**
  147. * @visible for testing.
  148. * Cache the response to an HTTP request if it is cacheable.
  149. * @param Google_HttpRequest $request
  150. * @return bool Returns true if the insertion was successful.
  151. * Otherwise, return false.
  152. */
  153. public function setCachedRequest(Google_HttpRequest $request) {
  154. // Determine if the request is cacheable.
  155. if (Google_CacheParser::isResponseCacheable($request)) {
  156. Google_Client::$cache->set($request->getCacheKey(), $request);
  157. return true;
  158. }
  159. return false;
  160. }
  161. /**
  162. * @visible for testing.
  163. * @param Google_HttpRequest $request
  164. * @return Google_HttpRequest|bool Returns the cached object or
  165. * false if the operation was unsuccessful.
  166. */
  167. public function getCachedRequest(Google_HttpRequest $request) {
  168. if (false == Google_CacheParser::isRequestCacheable($request)) {
  169. return false;
  170. }
  171. return Google_Client::$cache->get($request->getCacheKey());
  172. }
  173. /**
  174. * @param $respData
  175. * @param $headerSize
  176. * @return array
  177. */
  178. public static function parseHttpResponse($respData, $headerSize) {
  179. if (stripos($respData, self::CONNECTION_ESTABLISHED) !== false) {
  180. $respData = str_ireplace(self::CONNECTION_ESTABLISHED, '', $respData);
  181. }
  182. if ($headerSize) {
  183. $responseBody = substr($respData, $headerSize);
  184. $responseHeaders = substr($respData, 0, $headerSize);
  185. } else {
  186. list($responseHeaders, $responseBody) = explode("\r\n\r\n", $respData, 2);
  187. }
  188. $responseHeaders = self::parseResponseHeaders($responseHeaders);
  189. return array($responseHeaders, $responseBody);
  190. }
  191. public static function parseResponseHeaders($rawHeaders) {
  192. $responseHeaders = array();
  193. $responseHeaderLines = explode("\r\n", $rawHeaders);
  194. foreach ($responseHeaderLines as $headerLine) {
  195. if ($headerLine && strpos($headerLine, ':') !== false) {
  196. list($header, $value) = explode(': ', $headerLine, 2);
  197. $header = strtolower($header);
  198. if (isset($responseHeaders[$header])) {
  199. $responseHeaders[$header] .= "\n" . $value;
  200. } else {
  201. $responseHeaders[$header] = $value;
  202. }
  203. }
  204. }
  205. return $responseHeaders;
  206. }
  207. /**
  208. * @visible for testing
  209. * Process an http request that contains an enclosed entity.
  210. * @param Google_HttpRequest $request
  211. * @return Google_HttpRequest Processed request with the enclosed entity.
  212. */
  213. public function processEntityRequest(Google_HttpRequest $request) {
  214. $postBody = $request->getPostBody();
  215. $contentType = $request->getRequestHeader("content-type");
  216. // Set the default content-type as application/x-www-form-urlencoded.
  217. if (false == $contentType) {
  218. $contentType = self::FORM_URLENCODED;
  219. $request->setRequestHeaders(array('content-type' => $contentType));
  220. }
  221. // Force the payload to match the content-type asserted in the header.
  222. if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
  223. $postBody = http_build_query($postBody, '', '&');
  224. $request->setPostBody($postBody);
  225. }
  226. // Make sure the content-length header is set.
  227. if (!$postBody || is_string($postBody)) {
  228. $postsLength = strlen($postBody);
  229. $request->setRequestHeaders(array('content-length' => $postsLength));
  230. }
  231. return $request;
  232. }
  233. /**
  234. * Set options that update cURL's default behavior.
  235. * The list of accepted options are:
  236. * {@link http://php.net/manual/en/function.curl-setopt.php]
  237. *
  238. * @param array $optCurlParams Multiple options used by a cURL session.
  239. */
  240. public function setOptions($optCurlParams) {
  241. foreach ($optCurlParams as $key => $val) {
  242. $this->curlParams[$key] = $val;
  243. }
  244. }
  245. }