forked from sa4250mnpo70/dropbox-sdk-php
/
RequestUtil.php
302 lines (262 loc) · 9.81 KB
/
RequestUtil.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
<?php
namespace Dropbox;
if (!function_exists('curl_init')) {
throw new \Exception("The Dropbox SDK requires the cURL PHP extension, but it looks like you don't have it (couldn't find function \"curl_init\"). Library: \"" . __FILE__ . "\".");
}
if (!function_exists('json_decode')) {
throw new \Exception("The Dropbox SDK requires the JSON PHP extension, but it looks like you don't have it (couldn't find function \"json_decode\"). Library: \"" . __FILE__ . "\".");
}
// If mbstring.func_overload is set, it changes the behavior of the standard string functions in
// ways that makes this library break.
$mbstring_func_overload = ini_get("mbstring.func_overload");
if ($mbstring_func_overload & 2 == 2) {
throw new \Exception("The Dropbox SDK doesn't work when mbstring.func_overload is set to overload the standard string functions (value = ".var_export($mbstring_func_overload, true)."). Library: \"" . __FILE__ . "\".");
}
/* if (strlen((string) PHP_INT_MAX) < 19) {
// Looks like we're running on a 32-bit build of PHP. This could cause problems because some of the numbers
// we use (file sizes, quota, etc) can be larger than 32-bit ints can handle.
throw new \Exception("The Dropbox SDK uses 64-bit integers, but it looks like we're running on a version of PHP that doesn't support 64-bit integers (PHP_INT_MAX=" . ((string) PHP_INT_MAX) . "). Library: \"" . __FILE__ . "\"");
} */
/**
* @internal
*/
final class RequestUtil
{
/**
* @param string $userLocale
* @param string $host
* @param string $path
* @param array $params
* @return string
*/
static function buildUrlForGetOrPut($userLocale, $host, $path, $params = null)
{
$url = self::buildUri($host, $path);
$url .= "?locale=" . rawurlencode($userLocale);
if ($params !== null) {
foreach ($params as $key => $value) {
Checker::argStringNonEmpty("key in 'params'", $key);
if ($value !== null) {
if (is_bool($value)) {
$value = $value ? "true" : "false";
}
else if (is_int($value)) {
$value = (string) $value;
}
else if (!is_string($value)) {
throw new \InvalidArgumentException("params['$key'] is not a string, int, or bool");
}
$url .= "&" . rawurlencode($key) . "=" . rawurlencode($value);
}
}
}
return $url;
}
/**
* @param string $host
* @param string $path
* @return string
*/
static function buildUri($host, $path)
{
Checker::argStringNonEmpty("host", $host);
Checker::argStringNonEmpty("path", $path);
return "https://" . $host . "/" . $path;
}
/**
* @param string $clientIdentifier
* @param string $url
* @return Curl
*/
static function mkCurl($clientIdentifier, $url)
{
$curl = new Curl($url);
$curl->set(CURLOPT_CONNECTTIMEOUT, 10);
// If the transfer speed is below 1kB/sec for 10 sec, abort.
$curl->set(CURLOPT_LOW_SPEED_LIMIT, 1024);
$curl->set(CURLOPT_LOW_SPEED_TIME, 10);
//$curl->set(CURLOPT_VERBOSE, true); // For debugging.
// TODO: Figure out how to encode clientIdentifier (urlencode?)
$curl->addHeader("User-Agent: ".$clientIdentifier." Dropbox-PHP-SDK/".SdkVersion::VERSION);
return $curl;
}
/**
* @param string $clientIdentifier
* @param string $url
* @param string $authHeaderValue
* @return Curl
*/
static function mkCurlWithAuth($clientIdentifier, $url, $authHeaderValue)
{
$curl = self::mkCurl($clientIdentifier, $url);
$curl->addHeader("Authorization: $authHeaderValue");
return $curl;
}
/**
* @param string $clientIdentifier
* @param string $url
* @param string $accessToken
* @return Curl
*/
static function mkCurlWithOAuth($clientIdentifier, $url, $accessToken)
{
return self::mkCurlWithAuth($clientIdentifier, $url, "Bearer $accessToken");
}
static function buildPostBody($params)
{
if ($params === null) return "";
$pairs = array();
foreach ($params as $key => $value) {
Checker::argStringNonEmpty("key in 'params'", $key);
if ($value !== null) {
if (is_bool($value)) {
$value = $value ? "true" : "false";
}
else if (is_int($value)) {
$value = (string) $value;
}
else if (!is_string($value)) {
throw new \InvalidArgumentException("params['$key'] is not a string, int, or bool");
}
$pairs[] = rawurlencode($key) . "=" . rawurlencode((string) $value);
}
}
return implode("&", $pairs);
}
/**
* @param string $clientIdentifier
* @param string $accessToken
* @param string $userLocale
* @param string $host
* @param string $path
* @param array|null $params
*
* @return HttpResponse
*
* @throws Exception
*/
static function doPost($clientIdentifier, $accessToken, $userLocale, $host, $path, $params = null)
{
Checker::argStringNonEmpty("accessToken", $accessToken);
$url = self::buildUri($host, $path);
if ($params === null) $params = array();
$params['locale'] = $userLocale;
$curl = self::mkCurlWithOAuth($clientIdentifier, $url, $accessToken);
$curl->set(CURLOPT_POST, true);
$curl->set(CURLOPT_POSTFIELDS, self::buildPostBody($params));
$curl->set(CURLOPT_RETURNTRANSFER, true);
return $curl->exec();
}
/**
* @param string $clientIdentifier
* @param string $authHeaderValue
* @param string $userLocale
* @param string $host
* @param string $path
* @param array|null $params
*
* @return HttpResponse
*
* @throws Exception
*/
static function doPostWithSpecificAuth($clientIdentifier, $authHeaderValue, $userLocale, $host, $path, $params = null)
{
Checker::argStringNonEmpty("authHeaderValue", $authHeaderValue);
$url = self::buildUri($host, $path);
if ($params === null) $params = array();
$params['locale'] = $userLocale;
$curl = self::mkCurlWithAuth($clientIdentifier, $url, $authHeaderValue);
$curl->set(CURLOPT_POST, true);
$curl->set(CURLOPT_POSTFIELDS, self::buildPostBody($params));
$curl->set(CURLOPT_RETURNTRANSFER, true);
return $curl->exec();
}
/**
* @param string $clientIdentifier
* @param string $accessToken
* @param string $userLocale
* @param string $host
* @param string $path
* @param array|null $params
*
* @return HttpResponse
*
* @throws Exception
*/
static function doGet($clientIdentifier, $accessToken, $userLocale, $host, $path, $params = null)
{
Checker::argStringNonEmpty("accessToken", $accessToken);
$url = self::buildUrlForGetOrPut($userLocale, $host, $path, $params);
$curl = self::mkCurlWithOAuth($clientIdentifier, $url, $accessToken);
$curl->set(CURLOPT_HTTPGET, true);
$curl->set(CURLOPT_RETURNTRANSFER, true);
return $curl->exec();
}
/**
* @param string $responseBody
* @return mixed
* @throws Exception_BadResponse
*/
static function parseResponseJson($responseBody)
{
$obj = json_decode($responseBody, true, 10);
if ($obj === null) {
throw new Exception_BadResponse("Got bad JSON from server: $responseBody");
}
return $obj;
}
static function unexpectedStatus($httpResponse)
{
$sc = $httpResponse->statusCode;
$message = "HTTP status $sc";
if (is_string($httpResponse->body)) {
// TODO: Maybe only include the first ~200 chars of the body?
$message .= "\n".$httpResponse->body;
}
if ($sc === 400) return new Exception_BadRequest($message);
if ($sc === 401) return new Exception_InvalidAccessToken($message);
if ($sc === 500 || $sc === 502) return new Exception_ServerError($message);
if ($sc === 503) return new Exception_RetryLater($message);
if ($sc === 507) return new Exception_OverQuota($message);
return new Exception_BadResponseCode("Unexpected $message", $sc);
}
/**
* @param int $maxRetries
* The number of times to retry it the action if it fails with one of the transient
* API errors. A value of 1 means we'll try the action once and if it fails, we
* will retry once.
*
* @param callable $action
* The the action you want to retry.
*
* @return mixed
* Whatever is returned by the $action callable.
*/
static function runWithRetry($maxRetries, $action)
{
Checker::argNat("maxRetries", $maxRetries);
$retryDelay = 1;
$numRetries = 0;
while (true) {
try {
return $action();
}
// These exception types are the ones we think are possibly transient errors.
catch (Exception_NetworkIO $ex) {
$savedEx = $ex;
}
catch (Exception_ServerError $ex) {
$savedEx = $ex;
}
catch (Exception_RetryLater $ex) {
$savedEx = $ex;
}
// We maxed out our retries. Propagate the last exception we got.
if ($numRetries >= $maxRetries) throw $savedEx;
$numRetries++;
sleep($retryDelay);
$retryDelay *= 2; // Exponential back-off.
}
throw new \RuntimeException("unreachable");
}
}