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