MultiHttpClient: Also fallover to non-curl if curl_multi* is blocked
[lhc/web/wiklou.git] / includes / libs / http / MultiHttpClient.php
1 <?php
2 /**
3 * HTTP service client
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * Class to handle multiple HTTP requests
30 *
31 * If curl is available, requests will be made concurrently.
32 * Otherwise, they will be made serially.
33 *
34 * HTTP request maps are arrays that use the following format:
35 * - method : GET/HEAD/PUT/POST/DELETE
36 * - url : HTTP/HTTPS URL
37 * - query : <query parameter field/value associative array> (uses RFC 3986)
38 * - headers : <header name/value associative array>
39 * - body : source to get the HTTP request body from;
40 * this can simply be a string (always), a resource for
41 * PUT requests, and a field/value array for POST request;
42 * array bodies are encoded as multipart/form-data and strings
43 * use application/x-www-form-urlencoded (headers sent automatically)
44 * - stream : resource to stream the HTTP response body to
45 * - proxy : HTTP proxy to use
46 * - flags : map of boolean flags which supports:
47 * - relayResponseHeaders : write out header via header()
48 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
49 *
50 * @since 1.23
51 */
52 class MultiHttpClient implements LoggerAwareInterface {
53 /** @var resource */
54 protected $multiHandle = null; // curl_multi handle
55 /** @var string|null SSL certificates path */
56 protected $caBundlePath;
57 /** @var float */
58 protected $connTimeout = 10;
59 /** @var float */
60 protected $reqTimeout = 900;
61 /** @var bool */
62 protected $usePipelining = false;
63 /** @var int */
64 protected $maxConnsPerHost = 50;
65 /** @var string|null proxy */
66 protected $proxy;
67 /** @var string */
68 protected $userAgent = 'wikimedia/multi-http-client v1.0';
69 /** @var LoggerInterface */
70 protected $logger;
71
72 // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
73 // timeouts are periodically polled instead of being accurately respected.
74 // The select timeout is set to the minimum timeout multiplied by this factor.
75 const TIMEOUT_ACCURACY_FACTOR = 0.1;
76
77 /**
78 * @param array $options
79 * - connTimeout : default connection timeout (seconds)
80 * - reqTimeout : default request timeout (seconds)
81 * - proxy : HTTP proxy to use
82 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
83 * - maxConnsPerHost : maximum number of concurrent connections (per host)
84 * - userAgent : The User-Agent header value to send
85 * - logger : a \Psr\Log\LoggerInterface instance for debug logging
86 * - caBundlePath : path to specific Certificate Authority bundle (if any)
87 * @throws Exception
88 */
89 public function __construct( array $options ) {
90 if ( isset( $options['caBundlePath'] ) ) {
91 $this->caBundlePath = $options['caBundlePath'];
92 if ( !file_exists( $this->caBundlePath ) ) {
93 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
94 }
95 }
96 static $opts = [
97 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost',
98 'proxy', 'userAgent', 'logger'
99 ];
100 foreach ( $opts as $key ) {
101 if ( isset( $options[$key] ) ) {
102 $this->$key = $options[$key];
103 }
104 }
105 if ( $this->logger === null ) {
106 $this->logger = new NullLogger;
107 }
108 }
109
110 /**
111 * Execute an HTTP(S) request
112 *
113 * This method returns a response map of:
114 * - code : HTTP response code or 0 if there was a serious error
115 * - reason : HTTP response reason (empty if there was a serious error)
116 * - headers : <header name/value associative array>
117 * - body : HTTP response body or resource (if "stream" was set)
118 * - error : Any error string
119 * The map also stores integer-indexed copies of these values. This lets callers do:
120 * @code
121 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
122 * @endcode
123 * @param array $req HTTP request array
124 * @param array $opts
125 * - connTimeout : connection timeout per request (seconds)
126 * - reqTimeout : post-connection timeout per request (seconds)
127 * @return array Response array for request
128 */
129 public function run( array $req, array $opts = [] ) {
130 return $this->runMulti( [ $req ], $opts )[0]['response'];
131 }
132
133 /**
134 * Execute a set of HTTP(S) requests.
135 *
136 * If curl is available, requests will be made concurrently.
137 * Otherwise, they will be made serially.
138 *
139 * The maps are returned by this method with the 'response' field set to a map of:
140 * - code : HTTP response code or 0 if there was a serious error
141 * - reason : HTTP response reason (empty if there was a serious error)
142 * - headers : <header name/value associative array>
143 * - body : HTTP response body or resource (if "stream" was set)
144 * - error : Any error string
145 * The map also stores integer-indexed copies of these values. This lets callers do:
146 * @code
147 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
148 * @endcode
149 * All headers in the 'headers' field are normalized to use lower case names.
150 * This is true for the request headers and the response headers. Integer-indexed
151 * method/URL entries will also be changed to use the corresponding string keys.
152 *
153 * @param array[] $reqs Map of HTTP request arrays
154 * @param array $opts
155 * - connTimeout : connection timeout per request (seconds)
156 * - reqTimeout : post-connection timeout per request (seconds)
157 * - usePipelining : whether to use HTTP pipelining if possible
158 * - maxConnsPerHost : maximum number of concurrent connections (per host)
159 * @return array $reqs With response array populated for each
160 * @throws Exception
161 */
162 public function runMulti( array $reqs, array $opts = [] ) {
163 $this->normalizeRequests( $reqs );
164 $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
165
166 if ( $this->isCurlEnabled() ) {
167 return $this->runMultiCurl( $reqs, $opts );
168 } else {
169 return $this->runMultiHttp( $reqs, $opts );
170 }
171 }
172
173 /**
174 * Determines if the curl extension is available
175 *
176 * @return bool true if curl is available, false otherwise.
177 */
178 protected function isCurlEnabled() {
179 // Explicitly test if curl_multi* is blocked, as some users' hosts provide
180 // them with a modified curl with the multi-threaded parts removed(!)
181 return extension_loaded( 'curl' ) && function_exists( 'curl_multi_init' );
182 }
183
184 /**
185 * Execute a set of HTTP(S) requests concurrently
186 *
187 * @see MultiHttpClient::runMulti()
188 *
189 * @param array[] $reqs Map of HTTP request arrays
190 * @param array $opts
191 * - connTimeout : connection timeout per request (seconds)
192 * - reqTimeout : post-connection timeout per request (seconds)
193 * - usePipelining : whether to use HTTP pipelining if possible
194 * - maxConnsPerHost : maximum number of concurrent connections (per host)
195 * @codingStandardsIgnoreStart
196 * @phan-param array{connTimeout?:int,reqTimeout?:int,usePipelining?:bool,maxConnsPerHost?:int} $opts
197 * @codingStandardsIgnoreEnd
198 * @return array $reqs With response array populated for each
199 * @throws Exception
200 * @suppress PhanTypeInvalidDimOffset
201 */
202 private function runMultiCurl( array $reqs, array $opts ) {
203 $chm = $this->getCurlMulti();
204
205 $selectTimeout = $this->getSelectTimeout( $opts );
206
207 // Add all of the required cURL handles...
208 $handles = [];
209 foreach ( $reqs as $index => &$req ) {
210 $handles[$index] = $this->getCurlHandle( $req, $opts );
211 if ( count( $reqs ) > 1 ) {
212 // https://github.com/guzzle/guzzle/issues/349
213 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
214 }
215 }
216 unset( $req ); // don't assign over this by accident
217
218 $indexes = array_keys( $reqs );
219 if ( isset( $opts['usePipelining'] ) ) {
220 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
221 }
222 if ( isset( $opts['maxConnsPerHost'] ) ) {
223 // Keep these sockets around as they may be needed later in the request
224 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
225 }
226
227 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
228 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
229 $infos = [];
230
231 foreach ( $batches as $batch ) {
232 // Attach all cURL handles for this batch
233 foreach ( $batch as $index ) {
234 curl_multi_add_handle( $chm, $handles[$index] );
235 }
236 // Execute the cURL handles concurrently...
237 $active = null; // handles still being processed
238 do {
239 // Do any available work...
240 do {
241 $mrc = curl_multi_exec( $chm, $active );
242 $info = curl_multi_info_read( $chm );
243 if ( $info !== false ) {
244 $infos[(int)$info['handle']] = $info;
245 }
246 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
247 // Wait (if possible) for available work...
248 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
249 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
250 usleep( 5000 ); // 5ms
251 }
252 } while ( $active > 0 && $mrc == CURLM_OK );
253 }
254
255 // Remove all of the added cURL handles and check for errors...
256 foreach ( $reqs as $index => &$req ) {
257 $ch = $handles[$index];
258 curl_multi_remove_handle( $chm, $ch );
259
260 if ( isset( $infos[(int)$ch] ) ) {
261 $info = $infos[(int)$ch];
262 $errno = $info['result'];
263 if ( $errno !== 0 ) {
264 $req['response']['error'] = "(curl error: $errno)";
265 if ( function_exists( 'curl_strerror' ) ) {
266 $req['response']['error'] .= " " . curl_strerror( $errno );
267 }
268 $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
269 $req['response']['error'] );
270 }
271 } else {
272 $req['response']['error'] = "(curl error: no status set)";
273 }
274
275 // For convenience with the list() operator
276 $req['response'][0] = $req['response']['code'];
277 $req['response'][1] = $req['response']['reason'];
278 $req['response'][2] = $req['response']['headers'];
279 $req['response'][3] = $req['response']['body'];
280 $req['response'][4] = $req['response']['error'];
281 curl_close( $ch );
282 // Close any string wrapper file handles
283 if ( isset( $req['_closeHandle'] ) ) {
284 fclose( $req['_closeHandle'] );
285 unset( $req['_closeHandle'] );
286 }
287 }
288 unset( $req ); // don't assign over this by accident
289
290 // Restore the default settings
291 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
292 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
293
294 return $reqs;
295 }
296
297 /**
298 * @param array &$req HTTP request map
299 * @codingStandardsIgnoreStart
300 * @phan-param array{url:string,proxy?:?string,query:mixed,method:string,body:string|resource,headers:string[],stream?:resource,flags:array} $req
301 * @codingStandardsIgnoreEnd
302 * @param array $opts
303 * - connTimeout : default connection timeout
304 * - reqTimeout : default request timeout
305 * @return resource
306 * @throws Exception
307 */
308 protected function getCurlHandle( array &$req, array $opts ) {
309 $ch = curl_init();
310
311 curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
312 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
313 curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
314 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
315 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
316 curl_setopt( $ch, CURLOPT_HEADER, 0 );
317 if ( !is_null( $this->caBundlePath ) ) {
318 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
319 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
320 }
321 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
322
323 $url = $req['url'];
324 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
325 if ( $query != '' ) {
326 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
327 }
328 curl_setopt( $ch, CURLOPT_URL, $url );
329 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
330 curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
331
332 if ( $req['method'] === 'PUT' ) {
333 curl_setopt( $ch, CURLOPT_PUT, 1 );
334 if ( is_resource( $req['body'] ) ) {
335 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
336 if ( isset( $req['headers']['content-length'] ) ) {
337 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
338 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
339 $req['headers']['transfer-encoding'] === 'chunks'
340 ) {
341 curl_setopt( $ch, CURLOPT_UPLOAD, true );
342 } else {
343 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
344 }
345 } elseif ( $req['body'] !== '' ) {
346 $fp = fopen( "php://temp", "wb+" );
347 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
348 rewind( $fp );
349 curl_setopt( $ch, CURLOPT_INFILE, $fp );
350 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
351 $req['_closeHandle'] = $fp; // remember to close this later
352 } else {
353 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
354 }
355 curl_setopt( $ch, CURLOPT_READFUNCTION,
356 function ( $ch, $fd, $length ) {
357 return (string)fread( $fd, $length );
358 }
359 );
360 } elseif ( $req['method'] === 'POST' ) {
361 curl_setopt( $ch, CURLOPT_POST, 1 );
362 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
363 } else {
364 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
365 throw new Exception( "HTTP body specified for a non PUT/POST request." );
366 }
367 $req['headers']['content-length'] = 0;
368 }
369
370 if ( !isset( $req['headers']['user-agent'] ) ) {
371 $req['headers']['user-agent'] = $this->userAgent;
372 }
373
374 $headers = [];
375 foreach ( $req['headers'] as $name => $value ) {
376 if ( strpos( $name, ': ' ) ) {
377 throw new Exception( "Headers cannot have ':' in the name." );
378 }
379 $headers[] = $name . ': ' . trim( $value );
380 }
381 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
382
383 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
384 function ( $ch, $header ) use ( &$req ) {
385 if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
386 header( $header );
387 }
388 $length = strlen( $header );
389 $matches = [];
390 if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
391 $req['response']['code'] = (int)$matches[2];
392 $req['response']['reason'] = trim( $matches[3] );
393 return $length;
394 }
395 if ( strpos( $header, ":" ) === false ) {
396 return $length;
397 }
398 list( $name, $value ) = explode( ":", $header, 2 );
399 $name = strtolower( $name );
400 $value = trim( $value );
401 if ( isset( $req['response']['headers'][$name] ) ) {
402 $req['response']['headers'][$name] .= ', ' . $value;
403 } else {
404 $req['response']['headers'][$name] = $value;
405 }
406 return $length;
407 }
408 );
409
410 // This works with both file and php://temp handles (unlike CURLOPT_FILE)
411 $hasOutputStream = isset( $req['stream'] );
412 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
413 function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
414 if ( $hasOutputStream ) {
415 return fwrite( $req['stream'], $data );
416 } else {
417 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
418 $req['response']['body'] .= $data;
419
420 return strlen( $data );
421 }
422 }
423 );
424
425 return $ch;
426 }
427
428 /**
429 * @return resource
430 * @throws Exception
431 */
432 protected function getCurlMulti() {
433 if ( !$this->multiHandle ) {
434 if ( !function_exists( 'curl_multi_init' ) ) {
435 throw new Exception( "PHP cURL function curl_multi_init missing. " .
436 "Check https://www.mediawiki.org/wiki/Manual:CURL" );
437 }
438 $cmh = curl_multi_init();
439 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
440 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
441 $this->multiHandle = $cmh;
442 }
443 return $this->multiHandle;
444 }
445
446 /**
447 * Execute a set of HTTP(S) requests sequentially.
448 *
449 * @see MultiHttpClient::runMulti()
450 * @todo Remove dependency on MediaWikiServices: use a separate HTTP client
451 * library or copy code from PhpHttpRequest
452 * @param array $reqs Map of HTTP request arrays
453 * @param array $opts
454 * - connTimeout : connection timeout per request (seconds)
455 * - reqTimeout : post-connection timeout per request (seconds)
456 * @return array $reqs With response array populated for each
457 * @throws Exception
458 */
459 private function runMultiHttp( array $reqs, array $opts = [] ) {
460 $httpOptions = [
461 'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
462 'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
463 'logger' => $this->logger,
464 'caInfo' => $this->caBundlePath,
465 ];
466 foreach ( $reqs as &$req ) {
467 $reqOptions = $httpOptions + [
468 'method' => $req['method'],
469 'proxy' => $req['proxy'] ?? $this->proxy,
470 'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
471 'postData' => $req['body'],
472 ];
473
474 $url = $req['url'];
475 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
476 if ( $query != '' ) {
477 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
478 }
479
480 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
481 $url, $reqOptions );
482 $sv = $httpRequest->execute()->getStatusValue();
483
484 $respHeaders = array_map(
485 function ( $v ) {
486 return implode( ', ', $v );
487 },
488 $httpRequest->getResponseHeaders() );
489
490 $req['response'] = [
491 'code' => $httpRequest->getStatus(),
492 'reason' => '',
493 'headers' => $respHeaders,
494 'body' => $httpRequest->getContent(),
495 'error' => '',
496 ];
497
498 if ( !$sv->isOK() ) {
499 $svErrors = $sv->getErrors();
500 if ( isset( $svErrors[0] ) ) {
501 $req['response']['error'] = $svErrors[0]['message'];
502
503 // param values vary per failure type (ex. unknown host vs unknown page)
504 if ( isset( $svErrors[0]['params'][0] ) ) {
505 if ( is_numeric( $svErrors[0]['params'][0] ) ) {
506 if ( isset( $svErrors[0]['params'][1] ) ) {
507 // @phan-suppress-next-line PhanTypeInvalidDimOffset
508 $req['response']['reason'] = $svErrors[0]['params'][1];
509 }
510 } else {
511 $req['response']['reason'] = $svErrors[0]['params'][0];
512 }
513 }
514 }
515 }
516
517 $req['response'][0] = $req['response']['code'];
518 $req['response'][1] = $req['response']['reason'];
519 $req['response'][2] = $req['response']['headers'];
520 $req['response'][3] = $req['response']['body'];
521 $req['response'][4] = $req['response']['error'];
522 }
523
524 return $reqs;
525 }
526
527 /**
528 * Normalize request information
529 *
530 * @param array[] $reqs the requests to normalize
531 */
532 private function normalizeRequests( array &$reqs ) {
533 foreach ( $reqs as &$req ) {
534 $req['response'] = [
535 'code' => 0,
536 'reason' => '',
537 'headers' => [],
538 'body' => '',
539 'error' => ''
540 ];
541 if ( isset( $req[0] ) ) {
542 $req['method'] = $req[0]; // short-form
543 unset( $req[0] );
544 }
545 if ( isset( $req[1] ) ) {
546 $req['url'] = $req[1]; // short-form
547 unset( $req[1] );
548 }
549 if ( !isset( $req['method'] ) ) {
550 throw new Exception( "Request has no 'method' field set." );
551 } elseif ( !isset( $req['url'] ) ) {
552 throw new Exception( "Request has no 'url' field set." );
553 }
554 $this->logger->debug( "{$req['method']}: {$req['url']}" );
555 $req['query'] = $req['query'] ?? [];
556 $headers = []; // normalized headers
557 if ( isset( $req['headers'] ) ) {
558 foreach ( $req['headers'] as $name => $value ) {
559 $headers[strtolower( $name )] = $value;
560 }
561 }
562 $req['headers'] = $headers;
563 if ( !isset( $req['body'] ) ) {
564 $req['body'] = '';
565 $req['headers']['content-length'] = 0;
566 }
567 $req['flags'] = $req['flags'] ?? [];
568 }
569 }
570
571 /**
572 * Get a suitable select timeout for the given options.
573 *
574 * @param array $opts
575 * @return float
576 */
577 private function getSelectTimeout( $opts ) {
578 $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
579 $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
580 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
581 if ( count( $timeouts ) === 0 ) {
582 return 1;
583 }
584
585 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
586 // Minimum 10us for sanity
587 if ( $selectTimeout < 10e-6 ) {
588 $selectTimeout = 10e-6;
589 }
590 return $selectTimeout;
591 }
592
593 /**
594 * Register a logger
595 *
596 * @param LoggerInterface $logger
597 */
598 public function setLogger( LoggerInterface $logger ) {
599 $this->logger = $logger;
600 }
601
602 function __destruct() {
603 if ( $this->multiHandle ) {
604 curl_multi_close( $this->multiHandle );
605 }
606 }
607 }