Google_CurlIO

The Goolytics - Simple Google Analytics Google CurlIO class.

Defined (1)

The class is defined in the following location(s).

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