-
Notifications
You must be signed in to change notification settings - Fork 3
/
Request.php
578 lines (508 loc) · 19 KB
/
Request.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
577
578
<?php
namespace Unirest;
use Unirest\Method as Method;
use Unirest\Response as Response;
use Unirest\Exception as Exception;
class Request
{
private static $cookie = null;
private static $cookieFile = null;
private static $curlOpts = array();
private static $defaultHeaders = array();
private static $handle = null;
private static $jsonOpts = array();
private static $socketTimeout = null;
private static $verifyPeer = true;
private static $verifyHost = true;
private static $auth = array (
'user' => '',
'pass' => '',
'method' => CURLAUTH_BASIC
);
private static $proxy = array(
'port' => false,
'tunnel' => false,
'address' => false,
'type' => CURLPROXY_HTTP,
'auth' => array (
'user' => '',
'pass' => '',
'method' => CURLAUTH_BASIC
)
);
/**
* Set JSON decode mode
*
* @param bool $assoc When TRUE, returned objects will be converted into associative arrays.
* @param integer $depth User specified recursion depth.
* @param integer $options Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats)
* @return array
*/
public static function jsonOpts($assoc = false, $depth = 512, $options = 0)
{
return self::$jsonOpts = array($assoc, $depth, $options);
}
/**
* Verify SSL peer
*
* @param bool $enabled enable SSL verification, by default is true
* @return bool
*/
public static function verifyPeer($enabled)
{
return self::$verifyPeer = $enabled;
}
/**
* Verify SSL host
*
* @param bool $enabled enable SSL host verification, by default is true
* @return bool
*/
public static function verifyHost($enabled)
{
return self::$verifyHost = $enabled;
}
/**
* Set a timeout
*
* @param integer $seconds timeout value in seconds
* @return integer
*/
public static function timeout($seconds)
{
return self::$socketTimeout = $seconds;
}
/**
* Set default headers to send on every request
*
* @param array $headers headers array
*/
public static function defaultHeaders($headers)
{
return self::$defaultHeaders = array_merge(self::$defaultHeaders, $headers);
}
/**
* Set a new default header to send on every request
*
* @param string $name header name
* @param string $value header value
* @return string
*/
public static function defaultHeader($name, $value)
{
return self::$defaultHeaders[$name] = $value;
}
/**
* Clear all the default headers
*/
public static function clearDefaultHeaders()
{
return self::$defaultHeaders = array();
}
/**
* Set curl options to send on every request
*
* @param array $options options array
* @return array
*/
public static function curlOpts($options)
{
return self::mergeCurlOptions(self::$curlOpts, $options);
}
/**
* Set a new default header to send on every request
*
* @param string $name header name
* @param string $value header value
* @return string
*/
public static function curlOpt($name, $value)
{
return self::$curlOpts[$name] = $value;
}
/**
* Clear all the default headers
*/
public static function clearCurlOpts()
{
return self::$curlOpts = array();
}
/**
* Set a Mashape key to send on every request as a header
* Obtain your Mashape key by browsing one of your Mashape applications on https://www.mashape.com
*
* Note: Mashape provides 2 keys for each application: a 'Testing' and a 'Production' one.
* Be aware of which key you are using and do not share your Production key.
*
* @param string $key Mashape key
* @return string
*/
public static function setMashapeKey($key)
{
return self::defaultHeader('X-Mashape-Key', $key);
}
/**
* Set a coockie string for enabling coockie handling
*
* @param string $cookie
*/
public static function cookie($cookie)
{
self::$cookie = $cookie;
}
/**
* Set a coockie file path for enabling coockie handling
*
* $cookieFile must be a correct path with write permission
*
* @param string $cookieFile - path to file for saving cookie
*/
public static function cookieFile($cookieFile)
{
self::$cookieFile = $cookieFile;
}
/**
* Set authentication method to use
*
* @param string $username authentication username
* @param string $password authentication password
* @param integer $method authentication method
*/
public static function auth($username = '', $password = '', $method = CURLAUTH_BASIC)
{
self::$auth['user'] = $username;
self::$auth['pass'] = $password;
self::$auth['method'] = $method;
}
/**
* Set proxy to use
*
* @param string $address proxy address
* @param integer $port proxy port
* @param integer $type (Available options for this are CURLPROXY_HTTP, CURLPROXY_HTTP_1_0 CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5_HOSTNAME)
* @param bool $tunnel enable/disable tunneling
*/
public static function proxy($address, $port = 1080, $type = CURLPROXY_HTTP, $tunnel = false)
{
self::$proxy['type'] = $type;
self::$proxy['port'] = $port;
self::$proxy['tunnel'] = $tunnel;
self::$proxy['address'] = $address;
}
/**
* Set proxy authentication method to use
*
* @param string $username authentication username
* @param string $password authentication password
* @param integer $method authentication method
*/
public static function proxyAuth($username = '', $password = '', $method = CURLAUTH_BASIC)
{
self::$proxy['auth']['user'] = $username;
self::$proxy['auth']['pass'] = $password;
self::$proxy['auth']['method'] = $method;
}
/**
* Send a GET request to a URL
*
* @param string $url URL to send the GET request to
* @param array $headers additional headers to send
* @param mixed $parameters parameters to send in the querystring
* @param string $username Authentication username (deprecated)
* @param string $password Authentication password (deprecated)
* @return Unirest\Response
*/
public static function get($url, $headers = array(), $parameters = null, $username = null, $password = null)
{
return self::send(Method::GET, $url, $parameters, $headers, $username, $password);
}
/**
* Send a HEAD request to a URL
* @param string $url URL to send the HEAD request to
* @param array $headers additional headers to send
* @param mixed $parameters parameters to send in the querystring
* @param string $username Basic Authentication username (deprecated)
* @param string $password Basic Authentication password (deprecated)
* @return Unirest\Response
*/
public static function head($url, $headers = array(), $parameters = null, $username = null, $password = null)
{
return self::send(Method::HEAD, $url, $parameters, $headers, $username, $password);
}
/**
* Send a OPTIONS request to a URL
* @param string $url URL to send the OPTIONS request to
* @param array $headers additional headers to send
* @param mixed $parameters parameters to send in the querystring
* @param string $username Basic Authentication username
* @param string $password Basic Authentication password
* @return Unirest\Response
*/
public static function options($url, $headers = array(), $parameters = null, $username = null, $password = null)
{
return self::send(Method::OPTIONS, $url, $parameters, $headers, $username, $password);
}
/**
* Send a CONNECT request to a URL
* @param string $url URL to send the CONNECT request to
* @param array $headers additional headers to send
* @param mixed $parameters parameters to send in the querystring
* @param string $username Basic Authentication username (deprecated)
* @param string $password Basic Authentication password (deprecated)
* @return Unirest\Response
*/
public static function connect($url, $headers = array(), $parameters = null, $username = null, $password = null)
{
return self::send(Method::CONNECT, $url, $parameters, $headers, $username, $password);
}
/**
* Send POST request to a URL
* @param string $url URL to send the POST request to
* @param array $headers additional headers to send
* @param mixed $body POST body data
* @param string $username Basic Authentication username (deprecated)
* @param string $password Basic Authentication password (deprecated)
* @return Unirest\Response response
*/
public static function post($url, $headers = array(), $body = null, $username = null, $password = null)
{
return self::send(Method::POST, $url, $body, $headers, $username, $password);
}
/**
* Send DELETE request to a URL
* @param string $url URL to send the DELETE request to
* @param array $headers additional headers to send
* @param mixed $body DELETE body data
* @param string $username Basic Authentication username (deprecated)
* @param string $password Basic Authentication password (deprecated)
* @return Unirest\Response
*/
public static function delete($url, $headers = array(), $body = null, $username = null, $password = null)
{
return self::send(Method::DELETE, $url, $body, $headers, $username, $password);
}
/**
* Send PUT request to a URL
* @param string $url URL to send the PUT request to
* @param array $headers additional headers to send
* @param mixed $body PUT body data
* @param string $username Basic Authentication username (deprecated)
* @param string $password Basic Authentication password (deprecated)
* @return Unirest\Response
*/
public static function put($url, $headers = array(), $body = null, $username = null, $password = null)
{
return self::send(Method::PUT, $url, $body, $headers, $username, $password);
}
/**
* Send PATCH request to a URL
* @param string $url URL to send the PATCH request to
* @param array $headers additional headers to send
* @param mixed $body PATCH body data
* @param string $username Basic Authentication username (deprecated)
* @param string $password Basic Authentication password (deprecated)
* @return Unirest\Response
*/
public static function patch($url, $headers = array(), $body = null, $username = null, $password = null)
{
return self::send(Method::PATCH, $url, $body, $headers, $username, $password);
}
/**
* Send TRACE request to a URL
* @param string $url URL to send the TRACE request to
* @param array $headers additional headers to send
* @param mixed $body TRACE body data
* @param string $username Basic Authentication username (deprecated)
* @param string $password Basic Authentication password (deprecated)
* @return Unirest\Response
*/
public static function trace($url, $headers = array(), $body = null, $username = null, $password = null)
{
return self::send(Method::TRACE, $url, $body, $headers, $username, $password);
}
/**
* This function is useful for serializing multidimensional arrays, and avoid getting
* the 'Array to string conversion' notice
* @param array|object $data array to flatten.
* @param bool|string $parent parent key or false if no parent
* @return array
*/
public static function buildHTTPCurlQuery($data, $parent = false)
{
$result = array();
if (is_object($data)) {
$data = get_object_vars($data);
}
foreach ($data as $key => $value) {
if ($parent) {
$new_key = sprintf('%s[%s]', $parent, $key);
} else {
$new_key = $key;
}
if (!$value instanceof \CURLFile and (is_array($value) or is_object($value))) {
$result = array_merge($result, self::buildHTTPCurlQuery($value, $new_key));
} else {
$result[$new_key] = $value;
}
}
return $result;
}
/**
* Send a cURL request
* @param Unirest\Method|string $method HTTP method to use
* @param string $url URL to send the request to
* @param mixed $body request body
* @param array $headers additional headers to send
* @param string $username Authentication username (deprecated)
* @param string $password Authentication password (deprecated)
* @throws Unirest\Exception if a cURL error occurs
* @return Unirest\Response
*/
public static function send($method, $url, $body = null, $headers = array(), $username = null, $password = null)
{
self::$handle = curl_init();
if ($method !== Method::GET) {
curl_setopt(self::$handle, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt(self::$handle, CURLOPT_POSTFIELDS, $body);
} elseif (is_array($body)) {
if (strpos($url, '?') !== false) {
$url .= '&';
} else {
$url .= '?';
}
$url .= urldecode(http_build_query(self::buildHTTPCurlQuery($body)));
}
$curl_base_options = [
CURLOPT_URL => self::encodeUrl($url),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_HTTPHEADER => self::getFormattedHeaders($headers),
CURLOPT_HEADER => true,
CURLOPT_SSL_VERIFYPEER => self::$verifyPeer,
//CURLOPT_SSL_VERIFYHOST accepts only 0 (false) or 2 (true). Future versions of libcurl will treat values 1 and 2 as equals
CURLOPT_SSL_VERIFYHOST => self::$verifyHost === false ? 0 : 2,
// If an empty string, '', is set, a header containing all supported encoding types is sent
CURLOPT_ENCODING => ''
];
curl_setopt_array(self::$handle, self::mergeCurlOptions($curl_base_options, self::$curlOpts));
if (self::$socketTimeout !== null) {
curl_setopt(self::$handle, CURLOPT_TIMEOUT, self::$socketTimeout);
}
if (self::$cookie) {
curl_setopt(self::$handle, CURLOPT_COOKIE, self::$cookie);
}
if (self::$cookieFile) {
curl_setopt(self::$handle, CURLOPT_COOKIEFILE, self::$cookieFile);
curl_setopt(self::$handle, CURLOPT_COOKIEJAR, self::$cookieFile);
}
// supporting deprecated http auth method
if (!empty($username)) {
curl_setopt_array(self::$handle, array(
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username . ':' . $password
));
}
if (!empty(self::$auth['user'])) {
curl_setopt_array(self::$handle, array(
CURLOPT_HTTPAUTH => self::$auth['method'],
CURLOPT_USERPWD => self::$auth['user'] . ':' . self::$auth['pass']
));
}
if (self::$proxy['address'] !== false) {
curl_setopt_array(self::$handle, array(
CURLOPT_PROXYTYPE => self::$proxy['type'],
CURLOPT_PROXY => self::$proxy['address'],
CURLOPT_PROXYPORT => self::$proxy['port'],
CURLOPT_HTTPPROXYTUNNEL => self::$proxy['tunnel'],
CURLOPT_PROXYAUTH => self::$proxy['auth']['method'],
CURLOPT_PROXYUSERPWD => self::$proxy['auth']['user'] . ':' . self::$proxy['auth']['pass']
));
}
$response = curl_exec(self::$handle);
$error = curl_error(self::$handle);
$info = self::getInfo();
if ($error) {
throw new Exception($error);
}
// Split the full response in its headers and body
$header_size = $info['header_size'];
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$httpCode = $info['http_code'];
return new Response($httpCode, $body, $header, self::$jsonOpts);
}
public static function getInfo($opt = false)
{
if ($opt) {
$info = curl_getinfo(self::$handle, $opt);
} else {
$info = curl_getinfo(self::$handle);
}
return $info;
}
public static function getCurlHandle()
{
return self::$handle;
}
public static function getFormattedHeaders($headers)
{
$formattedHeaders = array();
$combinedHeaders = array_change_key_case(array_merge(self::$defaultHeaders, (array) $headers));
foreach ($combinedHeaders as $key => $val) {
$formattedHeaders[] = self::getHeaderString($key, $val);
}
if (!array_key_exists('user-agent', $combinedHeaders)) {
$formattedHeaders[] = 'user-agent: unirest-php/2.0';
}
if (!array_key_exists('expect', $combinedHeaders)) {
$formattedHeaders[] = 'expect:';
}
return $formattedHeaders;
}
private static function getArrayFromQuerystring($query)
{
$query = preg_replace_callback('/(?:^|(?<=&))[^=[]+/', function ($match) {
return bin2hex(urldecode($match[0]));
}, $query);
parse_str($query, $values);
return array_combine(array_map('hex2bin', array_keys($values)), $values);
}
/**
* Ensure that a URL is encoded and safe to use with cURL
* @param string $url URL to encode
* @return string
*/
private static function encodeUrl($url)
{
$url_parsed = parse_url($url);
$scheme = $url_parsed['scheme'] . '://';
$host = $url_parsed['host'];
$port = (isset($url_parsed['port']) ? $url_parsed['port'] : null);
$path = (isset($url_parsed['path']) ? $url_parsed['path'] : null);
$query = (isset($url_parsed['query']) ? $url_parsed['query'] : null);
if ($query !== null) {
$query = '?' . http_build_query(self::getArrayFromQuerystring($query));
}
if ($port && $port[0] !== ':') {
$port = ':' . $port;
}
$result = $scheme . $host . $port . $path . $query;
return $result;
}
private static function getHeaderString($key, $val)
{
$key = trim(strtolower($key));
return $key . ': ' . $val;
}
/**
* @param array $existing_options
* @param array $new_options
* @return array
*/
private static function mergeCurlOptions(&$existing_options, $new_options)
{
$existing_options = $new_options + $existing_options;
return $existing_options;
}
}