[ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * cURL HTTP transport 4 * 5 * @package Requests\Transport 6 */ 7 8 namespace WpOrg\Requests\Transport; 9 10 use RecursiveArrayIterator; 11 use RecursiveIteratorIterator; 12 use WpOrg\Requests\Capability; 13 use WpOrg\Requests\Exception; 14 use WpOrg\Requests\Exception\InvalidArgument; 15 use WpOrg\Requests\Exception\Transport\Curl as CurlException; 16 use WpOrg\Requests\Requests; 17 use WpOrg\Requests\Transport; 18 use WpOrg\Requests\Utility\InputValidator; 19 20 /** 21 * cURL HTTP transport 22 * 23 * @package Requests\Transport 24 */ 25 final class Curl implements Transport { 26 const CURL_7_10_5 = 0x070A05; 27 const CURL_7_16_2 = 0x071002; 28 29 /** 30 * Raw HTTP data 31 * 32 * @var string 33 */ 34 public $headers = ''; 35 36 /** 37 * Raw body data 38 * 39 * @var string 40 */ 41 public $response_data = ''; 42 43 /** 44 * Information on the current request 45 * 46 * @var array cURL information array, see {@link https://www.php.net/curl_getinfo} 47 */ 48 public $info; 49 50 /** 51 * cURL version number 52 * 53 * @var int 54 */ 55 public $version; 56 57 /** 58 * cURL handle 59 * 60 * @var resource|\CurlHandle Resource in PHP < 8.0, Instance of CurlHandle in PHP >= 8.0. 61 */ 62 private $handle; 63 64 /** 65 * Hook dispatcher instance 66 * 67 * @var \WpOrg\Requests\Hooks 68 */ 69 private $hooks; 70 71 /** 72 * Have we finished the headers yet? 73 * 74 * @var boolean 75 */ 76 private $done_headers = false; 77 78 /** 79 * If streaming to a file, keep the file pointer 80 * 81 * @var resource 82 */ 83 private $stream_handle; 84 85 /** 86 * How many bytes are in the response body? 87 * 88 * @var int 89 */ 90 private $response_bytes; 91 92 /** 93 * What's the maximum number of bytes we should keep? 94 * 95 * @var int|bool Byte count, or false if no limit. 96 */ 97 private $response_byte_limit; 98 99 /** 100 * Constructor 101 */ 102 public function __construct() { 103 $curl = curl_version(); 104 $this->version = $curl['version_number']; 105 $this->handle = curl_init(); 106 107 curl_setopt($this->handle, CURLOPT_HEADER, false); 108 curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1); 109 if ($this->version >= self::CURL_7_10_5) { 110 curl_setopt($this->handle, CURLOPT_ENCODING, ''); 111 } 112 if (defined('CURLOPT_PROTOCOLS')) { 113 // phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_protocolsFound 114 curl_setopt($this->handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); 115 } 116 if (defined('CURLOPT_REDIR_PROTOCOLS')) { 117 // phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_redir_protocolsFound 118 curl_setopt($this->handle, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); 119 } 120 } 121 122 /** 123 * Destructor 124 */ 125 public function __destruct() { 126 if (is_resource($this->handle)) { 127 curl_close($this->handle); 128 } 129 } 130 131 /** 132 * Perform a request 133 * 134 * @param string|Stringable $url URL to request 135 * @param array $headers Associative array of request headers 136 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD 137 * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation 138 * @return string Raw HTTP result 139 * 140 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $url argument is not a string or Stringable. 141 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $headers argument is not an array. 142 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $data parameter is not an array or string. 143 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array. 144 * @throws \WpOrg\Requests\Exception On a cURL error (`curlerror`) 145 */ 146 public function request($url, $headers = [], $data = [], $options = []) { 147 if (InputValidator::is_string_or_stringable($url) === false) { 148 throw InvalidArgument::create(1, '$url', 'string|Stringable', gettype($url)); 149 } 150 151 if (is_array($headers) === false) { 152 throw InvalidArgument::create(2, '$headers', 'array', gettype($headers)); 153 } 154 155 if (!is_array($data) && !is_string($data)) { 156 if ($data === null) { 157 $data = ''; 158 } else { 159 throw InvalidArgument::create(3, '$data', 'array|string', gettype($data)); 160 } 161 } 162 163 if (is_array($options) === false) { 164 throw InvalidArgument::create(4, '$options', 'array', gettype($options)); 165 } 166 167 $this->hooks = $options['hooks']; 168 169 $this->setup_handle($url, $headers, $data, $options); 170 171 $options['hooks']->dispatch('curl.before_send', [&$this->handle]); 172 173 if ($options['filename'] !== false) { 174 // phpcs:ignore WordPress.PHP.NoSilencedErrors -- Silenced the PHP native warning in favour of throwing an exception. 175 $this->stream_handle = @fopen($options['filename'], 'wb'); 176 if ($this->stream_handle === false) { 177 $error = error_get_last(); 178 throw new Exception($error['message'], 'fopen'); 179 } 180 } 181 182 $this->response_data = ''; 183 $this->response_bytes = 0; 184 $this->response_byte_limit = false; 185 if ($options['max_bytes'] !== false) { 186 $this->response_byte_limit = $options['max_bytes']; 187 } 188 189 if (isset($options['verify'])) { 190 if ($options['verify'] === false) { 191 curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0); 192 curl_setopt($this->handle, CURLOPT_SSL_VERIFYPEER, 0); 193 } 194 elseif (is_string($options['verify'])) { 195 curl_setopt($this->handle, CURLOPT_CAINFO, $options['verify']); 196 } 197 } 198 199 if (isset($options['verifyname']) && $options['verifyname'] === false) { 200 curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0); 201 } 202 203 curl_exec($this->handle); 204 $response = $this->response_data; 205 206 $options['hooks']->dispatch('curl.after_send', []); 207 208 if (curl_errno($this->handle) === CURLE_WRITE_ERROR || curl_errno($this->handle) === CURLE_BAD_CONTENT_ENCODING) { 209 // Reset encoding and try again 210 curl_setopt($this->handle, CURLOPT_ENCODING, 'none'); 211 212 $this->response_data = ''; 213 $this->response_bytes = 0; 214 curl_exec($this->handle); 215 $response = $this->response_data; 216 } 217 218 $this->process_response($response, $options); 219 220 // Need to remove the $this reference from the curl handle. 221 // Otherwise \WpOrg\Requests\Transport\Curl won't be garbage collected and the curl_close() will never be called. 222 curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, null); 223 curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, null); 224 225 return $this->headers; 226 } 227 228 /** 229 * Send multiple requests simultaneously 230 * 231 * @param array $requests Request data 232 * @param array $options Global options 233 * @return array Array of \WpOrg\Requests\Response objects (may contain \WpOrg\Requests\Exception or string responses as well) 234 * 235 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $requests argument is not an array or iterable object with array access. 236 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array. 237 */ 238 public function request_multiple($requests, $options) { 239 // If you're not requesting, we can't get any responses ¯\_(ツ)_/¯ 240 if (empty($requests)) { 241 return []; 242 } 243 244 if (InputValidator::has_array_access($requests) === false || InputValidator::is_iterable($requests) === false) { 245 throw InvalidArgument::create(1, '$requests', 'array|ArrayAccess&Traversable', gettype($requests)); 246 } 247 248 if (is_array($options) === false) { 249 throw InvalidArgument::create(2, '$options', 'array', gettype($options)); 250 } 251 252 $multihandle = curl_multi_init(); 253 $subrequests = []; 254 $subhandles = []; 255 256 $class = get_class($this); 257 foreach ($requests as $id => $request) { 258 $subrequests[$id] = new $class(); 259 $subhandles[$id] = $subrequests[$id]->get_subrequest_handle($request['url'], $request['headers'], $request['data'], $request['options']); 260 $request['options']['hooks']->dispatch('curl.before_multi_add', [&$subhandles[$id]]); 261 curl_multi_add_handle($multihandle, $subhandles[$id]); 262 } 263 264 $completed = 0; 265 $responses = []; 266 $subrequestcount = count($subrequests); 267 268 $request['options']['hooks']->dispatch('curl.before_multi_exec', [&$multihandle]); 269 270 do { 271 $active = 0; 272 273 do { 274 $status = curl_multi_exec($multihandle, $active); 275 } 276 while ($status === CURLM_CALL_MULTI_PERFORM); 277 278 $to_process = []; 279 280 // Read the information as needed 281 while ($done = curl_multi_info_read($multihandle)) { 282 $key = array_search($done['handle'], $subhandles, true); 283 if (!isset($to_process[$key])) { 284 $to_process[$key] = $done; 285 } 286 } 287 288 // Parse the finished requests before we start getting the new ones 289 foreach ($to_process as $key => $done) { 290 $options = $requests[$key]['options']; 291 if ($done['result'] !== CURLE_OK) { 292 //get error string for handle. 293 $reason = curl_error($done['handle']); 294 $exception = new CurlException( 295 $reason, 296 CurlException::EASY, 297 $done['handle'], 298 $done['result'] 299 ); 300 $responses[$key] = $exception; 301 $options['hooks']->dispatch('transport.internal.parse_error', [&$responses[$key], $requests[$key]]); 302 } 303 else { 304 $responses[$key] = $subrequests[$key]->process_response($subrequests[$key]->response_data, $options); 305 306 $options['hooks']->dispatch('transport.internal.parse_response', [&$responses[$key], $requests[$key]]); 307 } 308 309 curl_multi_remove_handle($multihandle, $done['handle']); 310 curl_close($done['handle']); 311 312 if (!is_string($responses[$key])) { 313 $options['hooks']->dispatch('multiple.request.complete', [&$responses[$key], $key]); 314 } 315 $completed++; 316 } 317 } 318 while ($active || $completed < $subrequestcount); 319 320 $request['options']['hooks']->dispatch('curl.after_multi_exec', [&$multihandle]); 321 322 curl_multi_close($multihandle); 323 324 return $responses; 325 } 326 327 /** 328 * Get the cURL handle for use in a multi-request 329 * 330 * @param string $url URL to request 331 * @param array $headers Associative array of request headers 332 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD 333 * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation 334 * @return resource|\CurlHandle Subrequest's cURL handle 335 */ 336 public function &get_subrequest_handle($url, $headers, $data, $options) { 337 $this->setup_handle($url, $headers, $data, $options); 338 339 if ($options['filename'] !== false) { 340 $this->stream_handle = fopen($options['filename'], 'wb'); 341 } 342 343 $this->response_data = ''; 344 $this->response_bytes = 0; 345 $this->response_byte_limit = false; 346 if ($options['max_bytes'] !== false) { 347 $this->response_byte_limit = $options['max_bytes']; 348 } 349 $this->hooks = $options['hooks']; 350 351 return $this->handle; 352 } 353 354 /** 355 * Setup the cURL handle for the given data 356 * 357 * @param string $url URL to request 358 * @param array $headers Associative array of request headers 359 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD 360 * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation 361 */ 362 private function setup_handle($url, $headers, $data, $options) { 363 $options['hooks']->dispatch('curl.before_request', [&$this->handle]); 364 365 // Force closing the connection for old versions of cURL (<7.22). 366 if (!isset($headers['Connection'])) { 367 $headers['Connection'] = 'close'; 368 } 369 370 /** 371 * Add "Expect" header. 372 * 373 * By default, cURL adds a "Expect: 100-Continue" to most requests. This header can 374 * add as much as a second to the time it takes for cURL to perform a request. To 375 * prevent this, we need to set an empty "Expect" header. To match the behaviour of 376 * Guzzle, we'll add the empty header to requests that are smaller than 1 MB and use 377 * HTTP/1.1. 378 * 379 * https://curl.se/mail/lib-2017-07/0013.html 380 */ 381 if (!isset($headers['Expect']) && $options['protocol_version'] === 1.1) { 382 $headers['Expect'] = $this->get_expect_header($data); 383 } 384 385 $headers = Requests::flatten($headers); 386 387 if (!empty($data)) { 388 $data_format = $options['data_format']; 389 390 if ($data_format === 'query') { 391 $url = self::format_get($url, $data); 392 $data = ''; 393 } 394 elseif (!is_string($data)) { 395 $data = http_build_query($data, '', '&'); 396 } 397 } 398 399 switch ($options['type']) { 400 case Requests::POST: 401 curl_setopt($this->handle, CURLOPT_POST, true); 402 curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data); 403 break; 404 case Requests::HEAD: 405 curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']); 406 curl_setopt($this->handle, CURLOPT_NOBODY, true); 407 break; 408 case Requests::TRACE: 409 curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']); 410 break; 411 case Requests::PATCH: 412 case Requests::PUT: 413 case Requests::DELETE: 414 case Requests::OPTIONS: 415 default: 416 curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']); 417 if (!empty($data)) { 418 curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data); 419 } 420 } 421 422 // cURL requires a minimum timeout of 1 second when using the system 423 // DNS resolver, as it uses `alarm()`, which is second resolution only. 424 // There's no way to detect which DNS resolver is being used from our 425 // end, so we need to round up regardless of the supplied timeout. 426 // 427 // https://github.com/curl/curl/blob/4f45240bc84a9aa648c8f7243be7b79e9f9323a5/lib/hostip.c#L606-L609 428 $timeout = max($options['timeout'], 1); 429 430 if (is_int($timeout) || $this->version < self::CURL_7_16_2) { 431 curl_setopt($this->handle, CURLOPT_TIMEOUT, ceil($timeout)); 432 } 433 else { 434 // phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_timeout_msFound 435 curl_setopt($this->handle, CURLOPT_TIMEOUT_MS, round($timeout * 1000)); 436 } 437 438 if (is_int($options['connect_timeout']) || $this->version < self::CURL_7_16_2) { 439 curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT, ceil($options['connect_timeout'])); 440 } 441 else { 442 // phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_connecttimeout_msFound 443 curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT_MS, round($options['connect_timeout'] * 1000)); 444 } 445 curl_setopt($this->handle, CURLOPT_URL, $url); 446 curl_setopt($this->handle, CURLOPT_USERAGENT, $options['useragent']); 447 if (!empty($headers)) { 448 curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers); 449 } 450 if ($options['protocol_version'] === 1.1) { 451 curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); 452 } 453 else { 454 curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); 455 } 456 457 if ($options['blocking'] === true) { 458 curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, [$this, 'stream_headers']); 459 curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, [$this, 'stream_body']); 460 curl_setopt($this->handle, CURLOPT_BUFFERSIZE, Requests::BUFFER_SIZE); 461 } 462 } 463 464 /** 465 * Process a response 466 * 467 * @param string $response Response data from the body 468 * @param array $options Request options 469 * @return string|false HTTP response data including headers. False if non-blocking. 470 * @throws \WpOrg\Requests\Exception 471 */ 472 public function process_response($response, $options) { 473 if ($options['blocking'] === false) { 474 $fake_headers = ''; 475 $options['hooks']->dispatch('curl.after_request', [&$fake_headers]); 476 return false; 477 } 478 if ($options['filename'] !== false && $this->stream_handle) { 479 fclose($this->stream_handle); 480 $this->headers = trim($this->headers); 481 } 482 else { 483 $this->headers .= $response; 484 } 485 486 if (curl_errno($this->handle)) { 487 $error = sprintf( 488 'cURL error %s: %s', 489 curl_errno($this->handle), 490 curl_error($this->handle) 491 ); 492 throw new Exception($error, 'curlerror', $this->handle); 493 } 494 $this->info = curl_getinfo($this->handle); 495 496 $options['hooks']->dispatch('curl.after_request', [&$this->headers, &$this->info]); 497 return $this->headers; 498 } 499 500 /** 501 * Collect the headers as they are received 502 * 503 * @param resource|\CurlHandle $handle cURL handle 504 * @param string $headers Header string 505 * @return integer Length of provided header 506 */ 507 public function stream_headers($handle, $headers) { 508 // Why do we do this? cURL will send both the final response and any 509 // interim responses, such as a 100 Continue. We don't need that. 510 // (We may want to keep this somewhere just in case) 511 if ($this->done_headers) { 512 $this->headers = ''; 513 $this->done_headers = false; 514 } 515 $this->headers .= $headers; 516 517 if ($headers === "\r\n") { 518 $this->done_headers = true; 519 } 520 return strlen($headers); 521 } 522 523 /** 524 * Collect data as it's received 525 * 526 * @since 1.6.1 527 * 528 * @param resource|\CurlHandle $handle cURL handle 529 * @param string $data Body data 530 * @return integer Length of provided data 531 */ 532 public function stream_body($handle, $data) { 533 $this->hooks->dispatch('request.progress', [$data, $this->response_bytes, $this->response_byte_limit]); 534 $data_length = strlen($data); 535 536 // Are we limiting the response size? 537 if ($this->response_byte_limit) { 538 if ($this->response_bytes === $this->response_byte_limit) { 539 // Already at maximum, move on 540 return $data_length; 541 } 542 543 if (($this->response_bytes + $data_length) > $this->response_byte_limit) { 544 // Limit the length 545 $limited_length = ($this->response_byte_limit - $this->response_bytes); 546 $data = substr($data, 0, $limited_length); 547 } 548 } 549 550 if ($this->stream_handle) { 551 fwrite($this->stream_handle, $data); 552 } 553 else { 554 $this->response_data .= $data; 555 } 556 557 $this->response_bytes += strlen($data); 558 return $data_length; 559 } 560 561 /** 562 * Format a URL given GET data 563 * 564 * @param string $url 565 * @param array|object $data Data to build query using, see {@link https://www.php.net/http_build_query} 566 * @return string URL with data 567 */ 568 private static function format_get($url, $data) { 569 if (!empty($data)) { 570 $query = ''; 571 $url_parts = parse_url($url); 572 if (empty($url_parts['query'])) { 573 $url_parts['query'] = ''; 574 } 575 else { 576 $query = $url_parts['query']; 577 } 578 579 $query .= '&' . http_build_query($data, '', '&'); 580 $query = trim($query, '&'); 581 582 if (empty($url_parts['query'])) { 583 $url .= '?' . $query; 584 } 585 else { 586 $url = str_replace($url_parts['query'], $query, $url); 587 } 588 } 589 return $url; 590 } 591 592 /** 593 * Self-test whether the transport can be used. 594 * 595 * The available capabilities to test for can be found in {@see \WpOrg\Requests\Capability}. 596 * 597 * @codeCoverageIgnore 598 * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`. 599 * @return bool Whether the transport can be used. 600 */ 601 public static function test($capabilities = []) { 602 if (!function_exists('curl_init') || !function_exists('curl_exec')) { 603 return false; 604 } 605 606 // If needed, check that our installed curl version supports SSL 607 if (isset($capabilities[Capability::SSL]) && $capabilities[Capability::SSL]) { 608 $curl_version = curl_version(); 609 if (!(CURL_VERSION_SSL & $curl_version['features'])) { 610 return false; 611 } 612 } 613 614 return true; 615 } 616 617 /** 618 * Get the correct "Expect" header for the given request data. 619 * 620 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD. 621 * @return string The "Expect" header. 622 */ 623 private function get_expect_header($data) { 624 if (!is_array($data)) { 625 return strlen((string) $data) >= 1048576 ? '100-Continue' : ''; 626 } 627 628 $bytesize = 0; 629 $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data)); 630 631 foreach ($iterator as $datum) { 632 $bytesize += strlen((string) $datum); 633 634 if ($bytesize >= 1048576) { 635 return '100-Continue'; 636 } 637 } 638 639 return ''; 640 } 641 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated : Mon Dec 6 08:20:01 2021 | Cross-referenced by PHPXref |