This repository has been archived by the owner on Apr 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 134
/
ConsumerAbstract.php
309 lines (276 loc) · 9.58 KB
/
ConsumerAbstract.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
<?php
/**
* Abstract OAuth consumer
* @author Ben Tadiar <ben@handcraftedbyben.co.uk>
* @link https://github.com/benthedesigner/dropbox
* @package Dropbox\OAuth
* @subpackage Consumer
*/
namespace Dropbox\OAuth\Consumer;
use \Dropbox\API as API;
abstract class ConsumerAbstract
{
// Dropbox web endpoint
const WEB_URL = 'https://www.dropbox.com/1/';
// OAuth flow methods
const REQUEST_TOKEN_METHOD = 'oauth/request_token';
const AUTHORISE_METHOD = 'oauth/authorize';
const ACCESS_TOKEN_METHOD = 'oauth/access_token';
/**
* Signature method, either PLAINTEXT or HMAC-SHA1
* @var string
*/
private $sigMethod = 'PLAINTEXT';
/**
* Output file handle
* @var null|resource
*/
protected $outFile = null;
/**
* Input file handle
* @var null|resource
*/
protected $inFile = null;
/**
* Authenticate using 3-legged OAuth flow, firstly
* checking we don't already have tokens to use
* @return void
*/
protected function authenticate()
{
if ((!$this->storage->get('access_token'))) {
try {
$this->getAccessToken();
} catch(\Dropbox\Exception $e) {
$this->getRequestToken();
$this->authorise();
}
}
}
/**
* Acquire an unauthorised request token
* @link http://tools.ietf.org/html/rfc5849#section-2.1
* @return void
*/
public function getRequestToken()
{
// Nullify any request token we already have
$this->storage->set(null, 'request_token');
$url = API::API_URL . self::REQUEST_TOKEN_METHOD;
$response = $this->fetch('POST', $url, '');
$token = $this->parseTokenString($response['body']);
$this->storage->set($token, 'request_token');
}
/**
* Obtain user authorisation
* The user will be redirected to Dropbox' web endpoint
* @link http://tools.ietf.org/html/rfc5849#section-2.2
* @return void
*/
private function authorise()
{
// Only redirect if using CLI
if (PHP_SAPI !== 'cli') {
$url = $this->getAuthoriseUrl();
header('Location: ' . $url);
exit;
}
}
/**
* Build the user authorisation URL
* @return string
*/
public function getAuthoriseUrl()
{
// Get the request token
$token = $this->getToken();
// Prepare request parameters
$params = array(
'oauth_token' => $token->oauth_token,
'oauth_token_secret' => $token->oauth_token_secret,
'oauth_callback' => $this->callback,
);
// Build the URL and redirect the user
$query = '?' . http_build_query($params, '', '&');
$url = self::WEB_URL . self::AUTHORISE_METHOD . $query;
return $url;
}
/**
* Acquire an access token
* Tokens acquired at this point should be stored to
* prevent having to request new tokens for each API call
* @link http://tools.ietf.org/html/rfc5849#section-2.3
*/
public function getAccessToken()
{
// Get the signed request URL
$response = $this->fetch('POST', API::API_URL, self::ACCESS_TOKEN_METHOD);
$token = $this->parseTokenString($response['body']);
$this->storage->set($token, 'access_token');
}
/**
* Get the request/access token
* This will return the access/request token depending on
* which stage we are at in the OAuth flow, or a dummy object
* if we have not yet started the authentication process
* @return object stdClass
*/
private function getToken()
{
if (!$token = $this->storage->get('access_token')) {
if (!$token = $this->storage->get('request_token')) {
$token = new \stdClass();
$token->oauth_token = null;
$token->oauth_token_secret = null;
}
}
return $token;
}
/**
* Generate signed request URL
* See inline comments for description
* @link http://tools.ietf.org/html/rfc5849#section-3.4
* @param string $method HTTP request method
* @param string $url API endpoint to send the request to
* @param string $call API call to send
* @param array $additional Additional parameters as an associative array
* @return array
*/
protected function getSignedRequest($method, $url, $call, array $additional = array())
{
// Get the request/access token
$token = $this->getToken();
// Generate a random string for the request
$nonce = md5(microtime(true) . uniqid('', true));
// Prepare the standard request parameters
$params = array(
'oauth_consumer_key' => $this->consumerKey,
'oauth_token' => $token->oauth_token,
'oauth_signature_method' => $this->sigMethod,
'oauth_version' => '1.0',
// Generate nonce and timestamp if signature method is HMAC-SHA1
'oauth_timestamp' => ($this->sigMethod == 'HMAC-SHA1') ? time() : null,
'oauth_nonce' => ($this->sigMethod == 'HMAC-SHA1') ? $nonce : null,
);
// Merge with the additional request parameters
$params = array_merge($params, $additional);
ksort($params);
// URL encode each parameter to RFC3986 for use in the base string
$encoded = array();
foreach($params as $param => $value) {
if ($value !== null) {
// If the value is a file upload (prefixed with @), replace it with
// the destination filename, the file path will be sent in POSTFIELDS
if (isset($value[0]) && $value[0] === '@') $value = $params['filename'];
$encoded[] = $this->encode($param) . '=' . $this->encode($value);
} else {
unset($params[$param]);
}
}
// Build the first part of the string
$base = $method . '&' . $this->encode($url . $call) . '&';
// Re-encode the encoded parameter string and append to $base
$base .= $this->encode(implode('&', $encoded));
// Concatenate the secrets with an ampersand
$key = $this->consumerSecret . '&' . $token->oauth_token_secret;
// Get the signature string based on signature method
$signature = $this->getSignature($base, $key);
$params['oauth_signature'] = $signature;
// Build the signed request URL
$query = '?' . http_build_query($params, '', '&');
return array(
'url' => $url . $call . $query,
'postfields' => $params,
);
}
/**
* Generate the oauth_signature for a request
* @param string $base Signature base string, used by HMAC-SHA1
* @param string $key Concatenated consumer and token secrets
*/
private function getSignature($base, $key)
{
switch ($this->sigMethod) {
case 'PLAINTEXT':
$signature = $key;
break;
case 'HMAC-SHA1':
$signature = base64_encode(hash_hmac('sha1', $base, $key, true));
break;
}
return $signature;
}
/**
* Set the OAuth signature method
* @param string $method Either PLAINTEXT or HMAC-SHA1
* @return void
*/
public function setSignatureMethod($method)
{
$method = strtoupper($method);
switch ($method) {
case 'PLAINTEXT':
case 'HMAC-SHA1':
$this->sigMethod = $method;
break;
default:
throw new \Dropbox\Exception('Unsupported signature method ' . $method);
}
}
/**
* Set the output file
* @param resource Resource to stream response data to
* @return void
*/
public function setOutFile($handle)
{
if (!is_resource($handle) || get_resource_type($handle) != 'stream') {
throw new \Dropbox\Exception('Outfile must be a stream resource');
}
$this->outFile = $handle;
}
/**
* Set the input file
* @param resource Resource to read data from
* @return void
*/
public function setInFile($handle)
{
if (!is_resource($handle) || get_resource_type($handle) != 'stream') {
throw new \Dropbox\Exception('Infile must be a stream resource');
}
fseek($handle, 0);
$this->inFile = $handle;
}
/**
* Parse response parameters for a token into an object
* Dropbox returns tokens in the response parameters, and
* not a JSON encoded object as per other API requests
* @link http://oauth.net/core/1.0/#response_parameters
* @param string $response
* @return object stdClass
*/
private function parseTokenString($response)
{
$parts = explode('&', $response);
$token = new \stdClass();
foreach ($parts as $part) {
list($k, $v) = explode('=', $part, 2);
$k = strtolower($k);
$token->$k = $v;
}
return $token;
}
/**
* Encode a value to RFC3986
* This is a convenience method to decode ~ symbols encoded
* by rawurldecode. This will encode all characters except
* the unreserved set, ALPHA, DIGIT, '-', '.', '_', '~'
* @link http://tools.ietf.org/html/rfc5849#section-3.6
* @param mixed $value
*/
private function encode($value)
{
return str_replace('%7E', '~', rawurlencode($value));
}
}