AbstractCurl.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. namespace Buzz\Client;
  3. use Buzz\Converter\HeaderConverter;
  4. use Buzz\Converter\RequestConverter;
  5. use Buzz\Converter\ResponseConverter;
  6. use Buzz\Message\Form\FormRequestInterface;
  7. use Buzz\Message\Form\FormUploadInterface;
  8. use Buzz\Message\MessageInterface;
  9. use Buzz\Message\RequestInterface as BuzzRequestInterface;
  10. use Buzz\Exception\ClientException;
  11. use Buzz\Message\Response;
  12. use Psr\Http\Message\RequestInterface;
  13. use Psr\Http\Message\ResponseInterface;
  14. /**
  15. * Base client class with helpers for working with cURL.
  16. */
  17. abstract class AbstractCurl extends AbstractClient
  18. {
  19. protected $options = array();
  20. public function __construct()
  21. {
  22. if (defined('CURLOPT_PROTOCOLS')) {
  23. $this->options = array(
  24. CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
  25. CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
  26. );
  27. }
  28. }
  29. /**
  30. * Creates a new cURL resource.
  31. *
  32. * @see curl_init()
  33. *
  34. * @return resource A new cURL resource
  35. *
  36. * @throws ClientException If unable to create a cURL resource
  37. */
  38. protected static function createCurlHandle()
  39. {
  40. if (false === $curl = curl_init()) {
  41. throw new ClientException('Unable to create a new cURL handle');
  42. }
  43. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  44. curl_setopt($curl, CURLOPT_HEADER, true);
  45. return $curl;
  46. }
  47. /**
  48. * Populates a response object.
  49. *
  50. * @param resource $curl A cURL resource
  51. * @param string $raw The raw response string
  52. * @param MessageInterface $response The response object
  53. *
  54. * @deprecated Will be removed in 1.0. Use createResponse instead.
  55. */
  56. protected static function populateResponse($curl, $raw, MessageInterface $response)
  57. {
  58. @trigger_error('AbstractCurl::populateResponse() is deprecated. Use AbstractCurl::createResponse instead.', E_USER_DEPRECATED);
  59. // fixes bug https://sourceforge.net/p/curl/bugs/1204/
  60. $version = curl_version();
  61. if (version_compare($version['version'], '7.30.0', '<')) {
  62. $pos = strlen($raw) - curl_getinfo($curl, CURLINFO_SIZE_DOWNLOAD);
  63. } else {
  64. $pos = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
  65. }
  66. $response->setHeaders(static::getLastHeaders(rtrim(substr($raw, 0, $pos))));
  67. $response->setContent(strlen($raw) > $pos ? substr($raw, $pos) : '');
  68. }
  69. /**
  70. * @param $curl
  71. * @param $raw
  72. * @return ResponseInterface
  73. */
  74. protected function createResponse($curl, $raw)
  75. {
  76. // fixes bug https://sourceforge.net/p/curl/bugs/1204/
  77. $version = curl_version();
  78. if (version_compare($version['version'], '7.30.0', '<')) {
  79. $pos = strlen($raw) - curl_getinfo($curl, CURLINFO_SIZE_DOWNLOAD);
  80. } else {
  81. $pos = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
  82. }
  83. // TODO rewrite me to avoid using BuzzRequest
  84. $response = new Response();
  85. $response->setHeaders(static::getLastHeaders(rtrim(substr($raw, 0, $pos))));
  86. $response->setContent(strlen($raw) > $pos ? substr($raw, $pos) : '');
  87. $response = ResponseConverter::psr7($response);
  88. return $response;
  89. }
  90. /**
  91. * Sets options on a cURL resource based on a request.
  92. *
  93. * @param resource $curl A cURL resource
  94. * @param RequestInterface $request A request object
  95. */
  96. private static function setOptionsFromRequest($curl, RequestInterface $request)
  97. {
  98. $options = array(
  99. CURLOPT_HTTP_VERSION => $request->getProtocolVersion() == 1.0 ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1,
  100. CURLOPT_CUSTOMREQUEST => $request->getMethod(),
  101. CURLOPT_URL => $request->getUri()->__toString(),
  102. CURLOPT_HTTPHEADER => HeaderConverter::toBuzzHeaders($request->getHeaders()),
  103. );
  104. switch ($request->getMethod()) {
  105. case BuzzRequestInterface::METHOD_HEAD:
  106. $options[CURLOPT_NOBODY] = true;
  107. break;
  108. case BuzzRequestInterface::METHOD_GET:
  109. $options[CURLOPT_HTTPGET] = true;
  110. break;
  111. case BuzzRequestInterface::METHOD_POST:
  112. case BuzzRequestInterface::METHOD_PUT:
  113. case BuzzRequestInterface::METHOD_DELETE:
  114. case BuzzRequestInterface::METHOD_PATCH:
  115. case BuzzRequestInterface::METHOD_OPTIONS:
  116. $options[CURLOPT_POSTFIELDS] = $fields = static::getPostFields($request);
  117. // remove the content-type header
  118. if (is_array($fields)) {
  119. $options[CURLOPT_HTTPHEADER] = array_filter($options[CURLOPT_HTTPHEADER], function($header) {
  120. return 0 !== stripos($header, 'Content-Type: ');
  121. });
  122. }
  123. break;
  124. }
  125. curl_setopt_array($curl, $options);
  126. }
  127. /**
  128. * Returns a value for the CURLOPT_POSTFIELDS option.
  129. *
  130. * @param RequestInterface $request A request object
  131. *
  132. * @return string|array A post fields value
  133. */
  134. private static function getPostFields(RequestInterface $request)
  135. {
  136. if (!$request instanceof FormRequestInterface) {
  137. return $request->getBody()->__toString();
  138. }
  139. // TODO move this code to request converter... I think...
  140. $fields = $request->getFields();
  141. $multipart = false;
  142. foreach ($fields as $name => $value) {
  143. if (!$value instanceof FormUploadInterface) {
  144. continue;
  145. }
  146. if (!$file = $value->getFile()) {
  147. return $request->getContent();
  148. }
  149. $multipart = true;
  150. if (version_compare(PHP_VERSION, '5.5', '>=')) {
  151. $curlFile = new \CURLFile($file);
  152. if ($contentType = $value->getContentType()) {
  153. $curlFile->setMimeType($contentType);
  154. }
  155. if (basename($file) != $value->getFilename()) {
  156. $curlFile->setPostFilename($value->getFilename());
  157. }
  158. $fields[$name] = $curlFile;
  159. } else {
  160. // replace value with upload string
  161. $fields[$name] = '@'.$file;
  162. if ($contentType = $value->getContentType()) {
  163. $fields[$name] .= ';type='.$contentType;
  164. }
  165. if (basename($file) != $value->getFilename()) {
  166. $fields[$name] .= ';filename='.$value->getFilename();
  167. }
  168. }
  169. }
  170. return $multipart ? $fields : http_build_query($fields, '', '&');
  171. }
  172. /**
  173. * A helper for getting the last set of headers.
  174. *
  175. * @param string $raw A string of many header chunks
  176. *
  177. * @return array An array of header lines
  178. */
  179. private static function getLastHeaders($raw)
  180. {
  181. $headers = array();
  182. foreach (preg_split('/(\\r?\\n)/', $raw) as $header) {
  183. if ($header) {
  184. $headers[] = $header;
  185. } else {
  186. $headers = array();
  187. }
  188. }
  189. return $headers;
  190. }
  191. /**
  192. * Stashes a cURL option to be set on send, when the resource is created.
  193. *
  194. * If the supplied value it set to null the option will be removed.
  195. *
  196. * @param integer $option The option
  197. * @param mixed $value The value
  198. *
  199. * @see curl_setopt()
  200. */
  201. public function setOption($option, $value)
  202. {
  203. if (null === $value) {
  204. unset($this->options[$option]);
  205. } else {
  206. $this->options[$option] = $value;
  207. }
  208. }
  209. /**
  210. * Prepares a cURL resource to send a request.
  211. *
  212. * @param $curl
  213. * @param RequestInterface $request
  214. * @param array $options
  215. */
  216. protected function prepare($curl, $request, array $options = array())
  217. {
  218. $request = RequestConverter::psr7($request);
  219. static::setOptionsFromRequest($curl, $request);
  220. // apply settings from client
  221. if ($this->getTimeout() < 1) {
  222. curl_setopt($curl, CURLOPT_TIMEOUT_MS, $this->getTimeout() * 1000);
  223. } else {
  224. curl_setopt($curl, CURLOPT_TIMEOUT, $this->getTimeout());
  225. }
  226. if ($this->proxy) {
  227. curl_setopt($curl, CURLOPT_PROXY, $this->proxy);
  228. }
  229. $canFollow = !ini_get('safe_mode') && !ini_get('open_basedir');
  230. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $canFollow && $this->getMaxRedirects() > 0);
  231. curl_setopt($curl, CURLOPT_MAXREDIRS, $canFollow ? $this->getMaxRedirects() : 0);
  232. curl_setopt($curl, CURLOPT_FAILONERROR, !$this->getIgnoreErrors());
  233. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->getVerifyPeer());
  234. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->getVerifyHost());
  235. // apply additional options
  236. curl_setopt_array($curl, $options + $this->options);
  237. }
  238. }