PluginProbe
InfiniteWP Client / trunk
InfiniteWP Client vtrunk
1.13.10 1.13.7 trunk 0.1.4 0.1.5 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.1.0 1.1.1 1.1.10 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 1.1.9 1.11.0 1.11.1 1.12.1 1.12.3 All 92 releases
iwp-client / lib / Dropbox2 / OAuth / Consumer / Curl.php

Curl.php in InfiniteWP Client trunk, at lib/Dropbox2/OAuth/Consumer/Curl.php

317 lines 14.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * OAuth consumer using PHP cURL
5 * @author Ben Tadiar <ben@handcraftedbyben.co.uk>
6 * @link https://github.com/benthedesigner/dropbox
7 * @package Dropbox\OAuth
8 * @subpackage Consumer
9 */
10 #[AllowDynamicProperties]
11 class Dropbox_Curl extends Dropbox_ConsumerAbstract
12 {
13 /**
14 * Default cURL options
15 * @var array
16 */
17 protected $defaultOptions = array(
18 CURLOPT_VERBOSE => true,
19 CURLOPT_HEADER => true,
20 CURLINFO_HEADER_OUT => false,
21 CURLOPT_RETURNTRANSFER => true,
22 CURLOPT_FOLLOWLOCATION => false,
23 );
24
25 /**
26 * Store the last response form the API
27 * @var mixed
28 */
29 protected $lastResponse = null;
30
31 /**
32 * Set properties and begin authentication
33 * @param string $key
34 * @param string $secret
35 * @param \Dropbox\OAuth\Consumer\StorageInterface $storage
36 * @param string $callback
37 */
38 public function __construct($key, $oauth2_id, $secret, Dropbox_StorageInterface $storage, $callback = null, $callbackhome = null, $deauthenticate = false, $instance_id = '', $old_auth = false)
39 {
40 // Check the cURL extension is loaded
41 if (!extension_loaded('curl')) {
42 throw new Dropbox_Exception('The cURL OAuth consumer requires the cURL extension. Please speak to your web hosting provider so that this missing PHP component can be installed.');
43 }
44
45 $this->consumerKey = $key;
46 $this->oauth2_id = $oauth2_id;
47 $this->consumerSecret = $secret;
48 $this->storage = $storage;
49 $this->callback = $callback;
50 $this->callbackhome = $callbackhome;
51 $this->instance_id = $instance_id;
52
53 if ($old_auth == false) {
54 if ($deauthenticate) {
55 $this->deauthenticate();
56 } else {
57 $this->authenticate();
58 }
59 }
60 }
61
62 /**
63 * Execute an API call
64 * @todo Improve error handling
65 * @param string $method The HTTP method
66 * @param string $url The API endpoint
67 * @param string $call The API method to call
68 * @param array $additional Additional parameters
69 * @return string|object stdClass
70 */
71 public function fetch($method, $url, $call, array $additional = array(), $retry_with_header = false)
72 {
73 // Get the signed request URL
74 $request = $this->getSignedRequest($method, $url, $call, $additional);
75
76 // Initialise and execute a cURL request
77 $handle = curl_init($request['url']);
78
79 // Get the default options array
80 $options = $this->defaultOptions;
81 if (!IWP_MMB_Backup_Options::get_iwp_backup_option('IWP_ssl_useservercerts')) {
82 $options[CURLOPT_CAINFO] = $GLOBALS['iwp_mmb_plugin_dir'].'/lib/cacert.pem';
83 }
84 if (IWP_MMB_Backup_Options::get_iwp_backup_option('IWP_ssl_disableverify')) {
85 $options[CURLOPT_SSL_VERIFYPEER] = false;
86 } else {
87 $options[CURLOPT_SSL_VERIFYPEER] = true;
88 }
89
90 if (!class_exists('WP_HTTP_Proxy')) require_once(ABSPATH.WPINC.'/class-http.php');
91 $proxy = new WP_HTTP_Proxy();
92
93 if ($proxy->is_enabled()) {
94 # WP_HTTP_Proxy returns empty strings if nothing is set
95 $user = $proxy->username();
96 $pass = $proxy->password();
97 $host = $proxy->host();
98 $port = (int)$proxy->port();
99 if (empty($port)) $port = 8080;
100 if (!empty($host) && $proxy->send_through_proxy($request['url'])) {
101 $options[CURLOPT_PROXY] = $host;
102 $options[CURLOPT_PROXYTYPE] = CURLPROXY_HTTP;
103 $options[CURLOPT_PROXYPORT] = $port;
104 if (!empty($user) && !empty($pass)) {
105 $options[CURLOPT_PROXYAUTH] = CURLAUTH_ANY;
106 $options[CURLOPT_PROXYUSERPWD] = sprintf('%s:%s', $user, $pass);
107 }
108 }
109 }
110
111 /*
112 Add check to see if it's an API v2 call if so then json encode the contents. This is so that it is backwards compatible with API v1 endpoints.
113 */
114 if (isset($additional['api_v2']) && !empty($request['postfields'])) {
115 $request['postfields'] = json_encode($request['postfields']);
116 }else{
117 // $key = array_search('Content-Type: application/json', $request['headers']);
118 // if (false !== $key) unset($request['headers'][$key]);// some users facing more delay.
119 if ($call == '2/users/get_space_usage') {
120 $request['postfields'] = json_encode(null);
121 }
122 }
123
124 if (isset($request['headers']) && !empty($request['headers'])) $options[CURLOPT_HTTPHEADER] = $request['headers'];
125
126 if ($method == 'GET' && $this->outFile) { // GET
127 $options[CURLOPT_RETURNTRANSFER] = false;
128 $options[CURLOPT_HEADER] = false;
129 $options[CURLOPT_FILE] = $this->outFile;
130 $options[CURLOPT_BINARYTRANSFER] = true;
131 $options[CURLOPT_FAILONERROR] = true;
132 $this->outFile = null;
133 } elseif ($method == 'POST' && $this->outFile) { // POST
134 $options[CURLOPT_POST] = true;
135 $options[CURLOPT_RETURNTRANSFER] = false;
136 $options[CURLOPT_HEADER] = false;
137 $options[CURLOPT_FILE] = $this->outFile;
138 $options[CURLOPT_BINARYTRANSFER] = true;
139 $options[CURLOPT_FAILONERROR] = true;
140 $this->outFile = null;
141 } elseif ($method == 'POST' && $this->inFile) { // POST
142 $options[CURLOPT_POST] = true;
143 $options[CURLOPT_POSTFIELDS] = $this->inFile;
144 } elseif ($method == 'POST') { // POST
145 $options[CURLOPT_POST] = true;
146 if (!empty($request['postfields'])) {
147 $options[CURLOPT_POSTFIELDS] = $request['postfields'];
148 } elseif (empty($additional['content_upload'])) {
149 // JSON representation of nullity
150 $options[CURLOPT_POSTFIELDS] = 'null';
151 } elseif ($retry_with_header) {
152 // It's a content upload, and there's no data. Versions of php-curl differ as to whether they add a Content-Length header automatically or not. Dropbox complains if it's not there. Here we have had a Dropbox 400 bad request returned so we try again with the header
153 $options[CURLOPT_HTTPHEADER] = array_merge($options[CURLOPT_HTTPHEADER], array('Content-Length: 0'));
154 }
155 } elseif ($method == 'PUT' && $this->inFile) { // PUT
156 $options[CURLOPT_PUT] = true;
157 $options[CURLOPT_INFILE] = $this->inFile;
158 // @todo Update so the data is not loaded into memory to get its size
159 $options[CURLOPT_INFILESIZE] = strlen(stream_get_contents($this->inFile));
160 fseek($this->inFile, 0);
161 $this->inFile = null;
162 }
163
164 if (isset($additional['timeout'])) {
165 $options[CURLOPT_TIMEOUT] = $additional['timeout'];
166 }
167
168 // Set the cURL options at once
169 curl_setopt_array($handle, $options);
170 // Execute, get any error and close
171 $response = curl_exec($handle);
172 $error = curl_error($handle);
173 $getinfo = curl_getinfo($handle);
174
175 curl_close($handle);
176
177 //Check if a cURL error has occured
178 if ($response === false) {
179 throw new Dropbox_CurlException($error);
180 } else {
181 // Parse the response if it is a string
182 if (is_string($response)) {
183 $response = $this->parse($response);
184 }
185
186 // Set the last response
187 $this->lastResponse = $response;
188
189 $code = (!empty($response['code'])) ? $response['code'] : $getinfo['http_code'];
190
191 // The API doesn't return an error message for the 304 status code...
192 // 304's are only returned when the path supplied during metadata calls has not been modified
193 if ($code == 304) {
194 $response['body'] = new stdClass;
195 $response['body']->error = 'The folder contents have not changed';
196 }
197
198 // Check if an error occurred and throw an Exception
199 if (!empty($response['body']->error) || $code >= 400) {
200 // Dropbox returns error messages inconsistently...
201 if (!empty($response['body']->error_summary)) {
202 $message = $response['body']->error_summary;
203 } elseif (!empty($response['body']->error) && $response['body']->error instanceof stdClass) {
204 $array = array_values((array) $response['body']->error);
205 //Dropbox API v2 only throws 409 errors if this error is a incorrect_offset then we need the entire error array not just the message. PHP Exception messages have to be a string so JSON encode the array.
206 $extract_message = (is_object($array[0]) && isset($array[0]->{'.tag'})) ? $array[0]->{'.tag'} : $array[0];
207 if (strpos($extract_message , 'incorrect_offset') !== false) {
208 $message = json_encode($array);
209 } elseif (strpos($extract_message , 'lookup_failed') !== false ) {
210 // re-structure the array so it is correctly formatted for API
211 // Note: Dropbox v2 returns different errors at different stages hence this fix
212 $correctOffset = array(
213 '0' => $array[1]->{'.tag'},
214 );
215 // the lookup_failed response doesn't always return a correct_offset this happens when the lookup fails because the session has been closed e.g the file has already been uploaded but the response didn't make it back to the client so we try again
216 if (isset($array[1]->correct_offset)) $correctOffset['1'] = $array[1]->correct_offset;
217
218 $message = json_encode($correctOffset);
219 } else {
220 $message = $extract_message;
221 }
222 } elseif (!empty($response['body']->error)) {
223 $message = $response['body']->error;
224 } elseif (is_string($response['body'])) {
225 // 31 Mar 2017 - This case has been found to exist; though the docs imply that there's always an 'error' property and that what is returned in JSON, we found a case of this being returned just as a simple string, but detectable via an HTTP 400: Error in call to API function "files/upload_session/append_v2": HTTP header "Dropbox-API-Arg": cursor.offset: expected integer, got string
226 $message = $response['body'];
227 } else {
228 $message = "HTTP bad response code: $code";
229 }
230
231 // Throw an Exception with the appropriate with the appropriate message and code
232 switch ($code) {
233 case 304:
234 throw new Dropbox_NotModifiedException($message, 304);
235 case 400:
236 if (!$retry_with_header) return $this->fetch($method, $url, $call, $additional, true);
237 throw new Dropbox_BadRequestException($message, 400);
238 case 404:
239 throw new Dropbox_NotFoundException($message, 404);
240 case 406:
241 throw new Dropbox_NotAcceptableException($message, 406);
242 case 415:
243 throw new Dropbox_UnsupportedMediaTypeException($message, 415);
244 case 401:
245 //401 means oauth token is expired continue to manually handle the exception depending on the situation
246 break;
247 case 409:
248 //409 in API V2 every error will return with a 409 to find out what the error is the error description should be checked.
249 throw new Dropbox_Exception($message, $code);
250 default:
251 throw new Dropbox_Exception($message, $code);
252 }
253 }
254
255 return $response;
256 }
257 }
258
259 /**
260 * Parse a cURL response
261 * @param string $response
262 * @return array
263 */
264 private function parse($response)
265 {
266 // Explode the response into headers and body parts (separated by double EOL)
267 list($headers, $response) = explode("\r\n\r\n", $response, 2);
268
269 // Explode response headers
270 $lines = explode("\r\n", $headers);
271
272 // If the status code is 100, the API server must send a final response
273 // We need to explode the response again to get the actual response
274 if (preg_match('#^HTTP/[\.\d]+ 100#i', $lines[0])) {
275 list($headers, $response) = explode("\r\n\r\n", $response, 2);
276 $lines = explode("\r\n", $headers);
277 }
278
279 // Get the HTTP response code from the first line
280 $first = array_shift($lines);
281 $pattern = '#^HTTP/[\.\d]+ ([0-9]{3})#i';
282 preg_match($pattern, $first, $matches);
283 $code = $matches[1];
284
285 // Parse the remaining headers into an associative array
286 $headers = array();
287 foreach ($lines as $line) {
288 list($k, $v) = explode(': ', $line, 2);
289 $headers[strtolower($k)] = $v;
290 }
291
292 // If the response body is not a JSON encoded string
293 // we'll return the entire response body
294 if (!$body = json_decode($response)) {
295 $body = $response;
296 }
297
298 if (is_string($body)) {
299 $body_lines = explode("\r\n", $body);
300 if (preg_match('#^HTTP/[\.\d]+ 100#i', $body_lines[0]) && preg_match('#^HTTP/\d#i', $body_lines[2])) {
301 return $this->parse($body);
302 }
303 }
304
305 return array('code' => $code, 'body' => $body, 'headers' => $headers);
306 }
307
308 /**
309 * Return the response for the last API request
310 * @return mixed
311 */
312 public function getlastResponse()
313 {
314 return $this->lastResponse;
315 }
316 }
317