This repository has been archived by the owner on Jan 30, 2020. It is now read-only.
/
Curl.php
576 lines (501 loc) · 18.9 KB
/
Curl.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
<?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Client\Adapter;
use Traversable;
use Zend\Http\Client\Adapter\AdapterInterface as HttpAdapter;
use Zend\Http\Client\Adapter\Exception as AdapterException;
use Zend\Stdlib\ArrayUtils;
/**
* An adapter class for Zend\Http\Client based on the curl extension.
* Curl requires libcurl. See for full requirements the PHP manual: http://php.net/curl
*/
class Curl implements HttpAdapter, StreamInterface
{
/**
* Operation timeout.
*
* @var int
*/
const ERROR_OPERATION_TIMEDOUT = 28;
/**
* Parameters array
*
* @var array
*/
protected $config = [];
/**
* What host/port are we connected to?
*
* @var array
*/
protected $connectedTo = [null, null];
/**
* The curl session handle
*
* @var resource|null
*/
protected $curl;
/**
* List of cURL options that should never be overwritten
*
* @var array
*/
protected $invalidOverwritableCurlOptions;
/**
* Response gotten from server
*
* @var string
*/
protected $response;
/**
* Stream for storing output
*
* @var resource
*/
protected $outputStream;
/**
* Adapter constructor
*
* Config is set using setOptions()
*
* @throws AdapterException\InitializationException
*/
public function __construct()
{
if (! extension_loaded('curl')) {
throw new AdapterException\InitializationException(
'cURL extension has to be loaded to use this Zend\Http\Client adapter'
);
}
$this->invalidOverwritableCurlOptions = [
CURLOPT_HTTPGET,
CURLOPT_POST,
CURLOPT_UPLOAD,
CURLOPT_CUSTOMREQUEST,
CURLOPT_HEADER,
CURLOPT_RETURNTRANSFER,
CURLOPT_HTTPHEADER,
CURLOPT_INFILE,
CURLOPT_INFILESIZE,
CURLOPT_PORT,
CURLOPT_MAXREDIRS,
CURLOPT_CONNECTTIMEOUT,
];
}
/**
* Set the configuration array for the adapter
*
* @param array|Traversable $options
* @return Curl
* @throws AdapterException\InvalidArgumentException
*/
public function setOptions($options = [])
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (! is_array($options)) {
throw new AdapterException\InvalidArgumentException(sprintf(
'Array or Traversable object expected, got %s',
gettype($options)
));
}
/** Config Key Normalization */
foreach ($options as $k => $v) {
unset($options[$k]); // unset original value
$options[str_replace(['-', '_', ' ', '.'], '', strtolower($k))] = $v; // replace w/ normalized
}
if (isset($options['proxyuser']) && isset($options['proxypass'])) {
$this->setCurlOption(CURLOPT_PROXYUSERPWD, $options['proxyuser'] . ':' . $options['proxypass']);
unset($options['proxyuser'], $options['proxypass']);
}
if (isset($options['sslverifypeer'])) {
$this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $options['sslverifypeer']);
unset($options['sslverifypeer']);
}
foreach ($options as $k => $v) {
$option = strtolower($k);
switch ($option) {
case 'proxyhost':
$this->setCurlOption(CURLOPT_PROXY, $v);
break;
case 'proxyport':
$this->setCurlOption(CURLOPT_PROXYPORT, $v);
break;
default:
if (is_array($v) && isset($this->config[$option]) && is_array($this->config[$option])) {
$v = ArrayUtils::merge($this->config[$option], $v);
}
$this->config[$option] = $v;
break;
}
}
return $this;
}
/**
* Retrieve the array of all configuration options
*
* @return array
*/
public function getConfig()
{
return $this->config;
}
/**
* Direct setter for cURL adapter related options.
*
* @param string|int $option
* @param mixed $value
* @return Curl
*/
public function setCurlOption($option, $value)
{
if (! isset($this->config['curloptions'])) {
$this->config['curloptions'] = [];
}
$this->config['curloptions'][$option] = $value;
return $this;
}
/**
* Initialize curl
*
* @param string $host
* @param int $port
* @param bool $secure
* @return void
* @throws AdapterException\RuntimeException if unable to connect
*/
public function connect($host, $port = 80, $secure = false)
{
// If we're already connected, disconnect first
if ($this->curl) {
$this->close();
}
// Do the actual connection
$this->curl = curl_init();
if ($port != 80) {
curl_setopt($this->curl, CURLOPT_PORT, intval($port));
}
if (isset($this->config['connecttimeout'])) {
$connectTimeout = $this->config['connecttimeout'];
} elseif (isset($this->config['timeout'])) {
$connectTimeout = $this->config['timeout'];
} else {
$connectTimeout = null;
}
if ($connectTimeout !== null && ! is_numeric($connectTimeout)) {
throw new AdapterException\InvalidArgumentException(sprintf(
'integer or numeric string expected, got %s',
gettype($connectTimeout)
));
}
if ($connectTimeout !== null) {
$connectTimeout = (int) $connectTimeout;
}
if ($connectTimeout !== null) {
if (defined('CURLOPT_CONNECTTIMEOUT_MS')) {
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT_MS, $connectTimeout * 1000);
} else {
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, $connectTimeout);
}
}
if (isset($this->config['timeout'])) {
if (defined('CURLOPT_TIMEOUT_MS')) {
curl_setopt($this->curl, CURLOPT_TIMEOUT_MS, $this->config['timeout'] * 1000);
} else {
curl_setopt($this->curl, CURLOPT_TIMEOUT, $this->config['timeout']);
}
}
if (isset($this->config['sslcafile']) && $this->config['sslcafile']) {
curl_setopt($this->curl, CURLOPT_CAINFO, $this->config['sslcafile']);
}
if (isset($this->config['sslcapath']) && $this->config['sslcapath']) {
curl_setopt($this->curl, CURLOPT_CAPATH, $this->config['sslcapath']);
}
if (isset($this->config['maxredirects'])) {
// Set Max redirects
curl_setopt($this->curl, CURLOPT_MAXREDIRS, $this->config['maxredirects']);
}
if (! $this->curl) {
$this->close();
throw new AdapterException\RuntimeException('Unable to Connect to ' . $host . ':' . $port);
}
if ($secure !== false) {
// Behave the same like Zend\Http\Adapter\Socket on SSL options.
if (isset($this->config['sslcert'])) {
curl_setopt($this->curl, CURLOPT_SSLCERT, $this->config['sslcert']);
}
if (isset($this->config['sslpassphrase'])) {
curl_setopt($this->curl, CURLOPT_SSLCERTPASSWD, $this->config['sslpassphrase']);
}
}
// Update connected_to
$this->connectedTo = [$host, $port];
}
/**
* Send request to the remote server
*
* @param string $method
* @param \Zend\Uri\Uri $uri
* @param float $httpVersion
* @param array $headers
* @param string $body
* @return string $request
* @throws AdapterException\RuntimeException If connection fails, connected
* to wrong host, no PUT file defined, unsupported method, or unsupported
* cURL option.
* @throws AdapterException\InvalidArgumentException if $method is currently not supported
* @throws AdapterException\TimeoutException if connection timed out
*/
public function write($method, $uri, $httpVersion = 1.1, $headers = [], $body = '')
{
// Make sure we're properly connected
if (! $this->curl) {
throw new AdapterException\RuntimeException('Trying to write but we are not connected');
}
if ($this->connectedTo[0] != $uri->getHost() || $this->connectedTo[1] != $uri->getPort()) {
throw new AdapterException\RuntimeException('Trying to write but we are connected to the wrong host');
}
// set URL
curl_setopt($this->curl, CURLOPT_URL, $uri->__toString());
// ensure correct curl call
$curlValue = true;
switch ($method) {
case 'GET':
$curlMethod = CURLOPT_HTTPGET;
break;
case 'POST':
$curlMethod = CURLOPT_POST;
break;
case 'PUT':
// There are two different types of PUT request, either a Raw Data string has been set
// or CURLOPT_INFILE and CURLOPT_INFILESIZE are used.
if (is_resource($body)) {
$this->config['curloptions'][CURLOPT_INFILE] = $body;
}
if (isset($this->config['curloptions'][CURLOPT_INFILE])) {
// Now we will probably already have Content-Length set, so that we have to delete it
// from $headers at this point:
if (! isset($headers['Content-Length'])
&& ! isset($this->config['curloptions'][CURLOPT_INFILESIZE])
) {
throw new AdapterException\RuntimeException(
'Cannot set a file-handle for cURL option CURLOPT_INFILE'
. ' without also setting its size in CURLOPT_INFILESIZE.'
);
}
if (isset($headers['Content-Length'])) {
$this->config['curloptions'][CURLOPT_INFILESIZE] = (int) $headers['Content-Length'];
unset($headers['Content-Length']);
}
if (is_resource($body)) {
$body = '';
}
$curlMethod = CURLOPT_UPLOAD;
} else {
$curlMethod = CURLOPT_CUSTOMREQUEST;
$curlValue = 'PUT';
}
break;
case 'PATCH':
$curlMethod = CURLOPT_CUSTOMREQUEST;
$curlValue = 'PATCH';
break;
case 'DELETE':
$curlMethod = CURLOPT_CUSTOMREQUEST;
$curlValue = 'DELETE';
break;
case 'OPTIONS':
$curlMethod = CURLOPT_CUSTOMREQUEST;
$curlValue = 'OPTIONS';
break;
case 'TRACE':
$curlMethod = CURLOPT_CUSTOMREQUEST;
$curlValue = 'TRACE';
break;
case 'HEAD':
$curlMethod = CURLOPT_CUSTOMREQUEST;
$curlValue = 'HEAD';
break;
default:
// For now, through an exception for unsupported request methods
throw new AdapterException\InvalidArgumentException(sprintf(
'Method \'%s\' currently not supported',
$method
));
}
if (is_resource($body) && $curlMethod != CURLOPT_UPLOAD) {
throw new AdapterException\RuntimeException('Streaming requests are allowed only with PUT');
}
// get http version to use
$curlHttp = $httpVersion == 1.1 ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0;
// mark as HTTP request and set HTTP method
curl_setopt($this->curl, CURLOPT_HTTP_VERSION, $curlHttp);
curl_setopt($this->curl, $curlMethod, $curlValue);
// Set the CURLINFO_HEADER_OUT flag so that we can retrieve the full request string later
curl_setopt($this->curl, CURLINFO_HEADER_OUT, true);
if ($this->outputStream) {
// headers will be read into the response
curl_setopt($this->curl, CURLOPT_HEADER, false);
curl_setopt($this->curl, CURLOPT_HEADERFUNCTION, [$this, 'readHeader']);
// and data will be written into the file
curl_setopt($this->curl, CURLOPT_FILE, $this->outputStream);
} else {
// ensure headers are also returned
curl_setopt($this->curl, CURLOPT_HEADER, true);
// ensure actual response is returned
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
}
// Treating basic auth headers in a special way
if (array_key_exists('Authorization', $headers) && 'Basic' == substr($headers['Authorization'], 0, 5)) {
curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($this->curl, CURLOPT_USERPWD, base64_decode(substr($headers['Authorization'], 6)));
unset($headers['Authorization']);
}
// set additional headers
if (! isset($headers['Accept'])) {
$headers['Accept'] = '';
}
$curlHeaders = [];
foreach ($headers as $key => $value) {
$curlHeaders[] = $key . ': ' . $value;
}
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $curlHeaders);
/**
* Make sure POSTFIELDS is set after $curlMethod is set:
* @link http://de2.php.net/manual/en/function.curl-setopt.php#81161
*/
if (in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], true)) {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $body);
} elseif ($curlMethod == CURLOPT_UPLOAD) {
// this covers a PUT by file-handle:
// Make the setting of this options explicit (rather than setting it through the loop following a bit lower)
// to group common functionality together.
curl_setopt($this->curl, CURLOPT_INFILE, $this->config['curloptions'][CURLOPT_INFILE]);
curl_setopt($this->curl, CURLOPT_INFILESIZE, $this->config['curloptions'][CURLOPT_INFILESIZE]);
unset($this->config['curloptions'][CURLOPT_INFILE]);
unset($this->config['curloptions'][CURLOPT_INFILESIZE]);
}
// set additional curl options
if (isset($this->config['curloptions'])) {
foreach ((array) $this->config['curloptions'] as $k => $v) {
if (! in_array($k, $this->invalidOverwritableCurlOptions)) {
if (curl_setopt($this->curl, $k, $v) == false) {
throw new AdapterException\RuntimeException(sprintf(
'Unknown or erroreous cURL option "%s" set',
$k
));
}
}
}
}
$this->response = '';
// send the request
$response = curl_exec($this->curl);
// if we used streaming, headers are already there
if (! is_resource($this->outputStream)) {
$this->response = $response;
}
$request = curl_getinfo($this->curl, CURLINFO_HEADER_OUT);
$request .= $body;
if ($response === false || empty($this->response)) {
if (curl_errno($this->curl) === static::ERROR_OPERATION_TIMEDOUT) {
throw new AdapterException\TimeoutException(
'Read timed out',
AdapterException\TimeoutException::READ_TIMEOUT
);
}
throw new AdapterException\RuntimeException(sprintf(
'Error in cURL request: %s',
curl_error($this->curl)
));
}
// separating header from body because it is dangerous to accidentially replace strings in the body
$responseHeaderSize = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE);
$responseHeaders = substr($this->response, 0, $responseHeaderSize);
// cURL automatically decodes chunked-messages, this means we have to
// disallow the Zend\Http\Response to do it again.
$responseHeaders = preg_replace("/Transfer-Encoding:\s*chunked\\r\\n/i", '', $responseHeaders);
// cURL can automatically handle content encoding; prevent double-decoding from occurring
if (isset($this->config['curloptions'][CURLOPT_ENCODING])
&& '' == $this->config['curloptions'][CURLOPT_ENCODING]
) {
$responseHeaders = preg_replace("/Content-Encoding:\s*gzip\\r\\n/i", '', $responseHeaders);
}
// cURL automatically handles Proxy rewrites, remove the "HTTP/1.0 200 Connection established" string:
$responseHeaders = preg_replace(
"/HTTP\/1.0\s*200\s*Connection\s*established\\r\\n\\r\\n/",
'',
$responseHeaders
);
// replace old header with new, cleaned up, header
$this->response = substr_replace($this->response, $responseHeaders, 0, $responseHeaderSize);
// Eliminate multiple HTTP responses.
do {
$parts = preg_split('|(?:\r?\n){2}|m', $this->response, 2);
$again = false;
if (isset($parts[1]) && preg_match("|^HTTP/1\.[01](.*?)\r\n|mi", $parts[1])) {
$this->response = $parts[1];
$again = true;
}
} while ($again);
return $request;
}
/**
* Return read response from server
*
* @return string
*/
public function read()
{
return $this->response;
}
/**
* Close the connection to the server
*
*/
public function close()
{
if (is_resource($this->curl)) {
curl_close($this->curl);
}
$this->curl = null;
$this->connectedTo = [null, null];
}
/**
* Get cUrl Handle
*
* @return resource
*/
public function getHandle()
{
return $this->curl;
}
/**
* Set output stream for the response
*
* @param resource $stream
* @return Curl
*/
public function setOutputStream($stream)
{
$this->outputStream = $stream;
return $this;
}
/**
* Header reader function for CURL
*
* @param resource $curl
* @param string $header
* @return int
*/
public function readHeader($curl, $header)
{
$this->response .= $header;
return strlen($header);
}
}