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
|
<?php
/**
* Dropbox API class
*
* @package Dropbox
* @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/dropbox-php/wiki/License MIT
*/
class Dropbox_API {
/**
* Sandbox root-path
*/
const ROOT_SANDBOX = 'sandbox';
/**
* Dropbox root-path
*/
const ROOT_DROPBOX = 'dropbox';
/**
* API URl
*/
protected $api_url = 'https://api.dropbox.com/1/';
/**
* Content API URl
*/
protected $api_content_url = 'https://api-content.dropbox.com/1/';
/**
* OAuth object
*
* @var Dropbox_OAuth
*/
protected $oauth;
/**
* Default root-path, this will most likely be 'sandbox' or 'dropbox'
*
* @var string
*/
protected $root;
protected $useSSL;
/**
* PHP is Safe Mode
*
* @var bool
*/
private $isSafeMode;
/**
* Chunked file size limit
*
* @var unknown
*/
public $chunkSize = 20971520; //20MB
/**
* Constructor
*
* @param Dropbox_OAuth Dropbox_Auth object
* @param string $root default root path (sandbox or dropbox)
*/
public function __construct(Dropbox_OAuth $oauth, $root = self::ROOT_DROPBOX, $useSSL = true) {
$this->oauth = $oauth;
$this->root = $root;
$this->useSSL = $useSSL;
$this->isSafeMode = (version_compare(PHP_VERSION, '5.4', '<') && get_cfg_var('safe_mode'));
if (!$this->useSSL)
{
throw new Dropbox_Exception('Dropbox REST API now requires that all requests use SSL');
}
}
/**
* Returns information about the current dropbox account
*
* @return stdclass
*/
public function getAccountInfo() {
$data = $this->oauth->fetch($this->api_url . 'account/info');
return json_decode($data['body'],true);
}
/**
* Returns a file's contents
*
* @param string $path path
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return string
*/
public function getFile($path = '', $root = null) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$result = $this->oauth->fetch($this->api_content_url . 'files/' . $root . '/' . ltrim($path,'/'));
return $result['body'];
}
/**
* Uploads a new file
*
* @param string $path Target path (including filename)
* @param string $file Either a path to a file or a stream resource
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return bool
*/
public function putFile($path, $file, $root = null) {
if (is_resource($file)) {
$stat = fstat($file);
$size = $stat['size'];
} else if (is_string($file) && is_readable($file)) {
$size = filesize($file);
} else {
throw new Dropbox_Exception('File must be a file-resource or a file path string');
}
if ($this->oauth->isPutSupport()) {
if ($size) {
if ($size > $this->chunkSize) {
$res = array('uploadID' => null, 'offset' => 0);
$i[$res['offset']] = 0;
while($i[$res['offset']] < 5) {
$res = $this->chunkedUpload($path, $file, $root, true, $res['offset'], $res['uploadID']);
if (isset($res['uploadID'])) {
if (!isset($i[$res['offset']])) {
$i[$res['offset']] = 0;
} else {
$i[$res['offset']]++;
}
} else {
break;
}
}
return true;
} else {
return $this->putStream($path, $file, $root);
}
}
}
if ($size > 157286400) {
// Dropbox API /files has a maximum file size limit of 150 MB.
// https://www.dropbox.com/developers/core/docs#files-POST
throw new Dropbox_Exception("Uploading file to Dropbox failed");
}
$directory = dirname($path);
$filename = basename($path);
if($directory==='.') $directory = '';
$directory = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($directory));
$filename = str_replace('~', '%7E', rawurlencode($filename));
if (is_null($root)) $root = $this->root;
if (is_string($file)) {
$file = fopen($file,'rb');
} elseif (!is_resource($file)) {
throw new Dropbox_Exception('File must be a file-resource or a file path string');
}
if (!$this->isSafeMode) {
set_time_limit(600);
}
$result=$this->multipartFetch($this->api_content_url . 'files/' .
$root . '/' . trim($directory,'/'), $file, $filename);
if(!isset($result["httpStatus"]) || $result["httpStatus"] != 200)
throw new Dropbox_Exception("Uploading file to Dropbox failed");
return true;
}
/**
* Uploads large files to Dropbox in mulitple chunks
*
* @param string $file Absolute path to the file to be uploaded
* @param string|bool $filename The destination filename of the uploaded file
* @param string $path Path to upload the file to, relative to root
* @param boolean $overwrite Should the file be overwritten? (Default: true)
* @return stdClass
*/
public function chunkedUpload($path, $handle, $root = null, $overwrite = true, $offset = 0, $uploadID = null)
{
if (is_string($handle) && is_readable($handle)) {
$handle = fopen($handle, 'rb');
}
if (is_resource($handle)) {
// Seek to the correct position on the file pointer
fseek($handle, $offset);
// Read from the file handle until EOF, uploading each chunk
while ($data = fread($handle, $this->chunkSize)) {
if (!$this->isSafeMode) {
set_time_limit(600);
}
// Open a temporary file handle and write a chunk of data to it
$chunkHandle = fopen('php://temp', 'rwb');
fwrite($chunkHandle, $data);
// Set the file, request parameters and send the request
$this->oauth->setInFile($chunkHandle);
$params = array('upload_id' => $uploadID, 'offset' => $offset);
try {
// Attempt to upload the current chunk
$res = $this->oauth->fetch($this->api_content_url . 'chunked_upload', $params, 'PUT');
$response = json_decode($res['body'], true);
} catch (Exception $e) {
$res = $this->oauth->getLastResponse();
if ($response['httpStatus'] == 400) {
// Incorrect offset supplied, return expected offset and upload ID
$response = json_decode($res['body'], true);
$uploadID = $response['upload_id'];
$offset = $response['offset'];
return array('uploadID' => $uploadID, 'offset' => $offset);
} else {
// Re-throw the caught Exception
throw $e;
}
throw $e;
}
// On subsequent chunks, use the upload ID returned by the previous request
if (isset($response['upload_id'])) {
$uploadID = $response['upload_id'];
}
// Set the data offset
if (isset($response['offset'])) {
$offset = $response['offset'];
}
// Close the file handle for this chunk
fclose($chunkHandle);
}
// Complete the chunked upload
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
if (is_null($root)) {
$root = $this->root;
}
$params = array('overwrite' => (int) $overwrite, 'upload_id' => $uploadID);
return $this->oauth->fetch($this->api_content_url . 'commit_chunked_upload/' .
$root . '/' . ltrim($path,'/'), $params, 'POST');
} else {
throw new Dropbox_Exception('Could not open ' . $handle . ' for reading');
}
}
/**
* Uploads file data from a stream
*
* Note: This function is experimental and requires further testing
* @param resource $stream A readable stream created using fopen()
* @param string $filename The destination filename, including path
* @param boolean $overwrite Should the file be overwritten? (Default: true)
* @return array
*/
public function putStream($path, $file, $root = null, $overwrite = true)
{
if ($this->isSafeMode) {
set_time_limit(600);
}
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
if (is_null($root)) {
$root = $this->root;
}
$params = array('overwrite' => (int) $overwrite);
$this->oauth->setInfile($file);
$result=$this->oauth->fetch($this->api_content_url . 'files_put/' .
$root . '/' . ltrim($path,'/'), $params, 'PUT');
if (!isset($result["httpStatus"]) || $result["httpStatus"] != 200) {
throw new Dropbox_Exception("Uploading file to Dropbox failed");
}
return true;
}
/**
* Copies a file or directory from one location to another
*
* This method returns the file information of the newly created file.
*
* @param string $from source path
* @param string $to destination path
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return stdclass
*/
public function copy($from, $to, $root = null) {
if (is_null($root)) $root = $this->root;
$response = $this->oauth->fetch($this->api_url . 'fileops/copy', array('from_path' => $from, 'to_path' => $to, 'root' => $root), 'POST');
return json_decode($response['body'],true);
}
/**
* Creates a new folder
*
* This method returns the information from the newly created directory
*
* @param string $path
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return stdclass
*/
public function createFolder($path, $root = null) {
if (is_null($root)) $root = $this->root;
// Making sure the path starts with a /
$path = '/' . ltrim($path,'/');
$response = $this->oauth->fetch($this->api_url . 'fileops/create_folder', array('path' => $path, 'root' => $root),'POST');
return json_decode($response['body'],true);
}
/**
* Deletes a file or folder.
*
* This method will return the metadata information from the deleted file or folder, if successful.
*
* @param string $path Path to new folder
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return array
*/
public function delete($path, $root = null) {
if (is_null($root)) $root = $this->root;
$response = $this->oauth->fetch($this->api_url . 'fileops/delete', array('path' => $path, 'root' => $root), 'POST');
return json_decode($response['body']);
}
/**
* Moves a file or directory to a new location
*
* This method returns the information from the newly created directory
*
* @param mixed $from Source path
* @param mixed $to destination path
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return stdclass
*/
public function move($from, $to, $root = null) {
if (is_null($root)) $root = $this->root;
$response = $this->oauth->fetch($this->api_url . 'fileops/move', array('from_path' => rawurldecode($from), 'to_path' => rawurldecode($to), 'root' => $root), 'POST');
return json_decode($response['body'],true);
}
/**
* Returns file and directory information
*
* @param string $path Path to receive information from
* @param bool $list When set to true, this method returns information from all files in a directory. When set to false it will only return infromation from the specified directory.
* @param string $hash If a hash is supplied, this method simply returns true if nothing has changed since the last request. Good for caching.
* @param int $fileLimit Maximum number of file-information to receive
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return array|true
*/
public function getMetaData($path, $list = true, $hash = null, $fileLimit = null, $root = null) {
if (is_null($root)) $root = $this->root;
$args = array(
'list' => $list,
);
if (!is_null($hash)) $args['hash'] = $hash;
if (!is_null($fileLimit)) $args['file_limit'] = $fileLimit;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$response = $this->oauth->fetch($this->api_url . 'metadata/' . $root . '/' . ltrim($path,'/'), $args);
/* 304 is not modified */
if ($response['httpStatus']==304) {
return true;
} else {
return json_decode($response['body'],true);
}
}
/**
* A way of letting you keep up with changes to files and folders in a user's Dropbox. You can periodically call /delta to get a list of "delta entries", which are instructions on how to update your local state to match the server's state.
*
* This method returns the information from the newly created directory
*
* @param string $cursor A string that is used to keep track of your current state. On the next call pass in this value to return delta entries that have been recorded since the cursor was returned.
* @return stdclass
*/
public function delta($cursor) {
$arg['cursor'] = $cursor;
$response = $this->oauth->fetch($this->api_url . 'delta', $arg, 'POST');
return json_decode($response['body'],true);
}
/**
* Returns a thumbnail (as a string) for a file path.
*
* @param string $path Path to file
* @param string $size small, medium or large
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return string
*/
public function getThumbnail($path, $size = 'small', $root = null) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$response = $this->oauth->fetch($this->api_content_url . 'thumbnails/' . $root . '/' . ltrim($path,'/'),array('size' => $size));
return $response['body'];
}
/**
* This method is used to generate multipart POST requests for file upload
*
* @param string $uri
* @param array $arguments
* @return bool
*/
protected function multipartFetch($uri, $file, $filename) {
/* random string */
$boundary = 'R50hrfBj5JYyfR3vF3wR96GPCC9Fd2q2pVMERvEaOE3D8LZTgLLbRpNwXek3';
$headers = array(
'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
);
$body="--" . $boundary . "\r\n";
$body.="Content-Disposition: form-data; name=file; filename=".rawurldecode($filename)."\r\n";
$body.="Content-type: application/octet-stream\r\n";
$body.="\r\n";
$body.=stream_get_contents($file);
$body.="\r\n";
$body.="--" . $boundary . "--";
// Dropbox requires the filename to also be part of the regular arguments, so it becomes
// part of the signature.
$uri.='?file=' . $filename;
return $this->oauth->fetch($uri, $body, 'POST', $headers);
}
/**
* Search
*
* Returns metadata for all files and folders that match the search query.
*
* @added by: diszo.sasil
*
* @param string $query
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @param string $path
* @return array
*/
public function search($query = '', $root = null, $path = ''){
if (is_null($root)) $root = $this->root;
if(!empty($path)){
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
}
$response = $this->oauth->fetch($this->api_url . 'search/' . $root . '/' . ltrim($path,'/'),array('query' => $query));
return json_decode($response['body'],true);
}
/**
* Creates and returns a shareable link to files or folders.
*
* Note: Links created by the /shares API call expire after thirty days.
*
* @param string $path
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @param string $short_url When true (default), the URL returned will be shortened using the Dropbox URL shortener
* @return array
*/
public function share($path, $root = null, $short_url = true) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$short_url = ((is_string($short_url) && strtolower($short_url) === 'false') || !$short_url)? 'false' : 'true';
$response = $this->oauth->fetch($this->api_url. 'shares/'. $root . '/' . ltrim($path, '/'), array('short_url' => $short_url), 'POST');
return json_decode($response['body'],true);
}
/**
* Returns a link directly to a file.
* Similar to /shares. The difference is that this bypasses the Dropbox webserver, used to provide a preview of the file, so that you can effectively stream the contents of your media.
*
* Note: The /media link expires after four hours, allotting enough time to stream files, but not enough to leave a connection open indefinitely.
*
* @param type $path
* @param type $root
* @return type
*/
public function media($path, $root = null) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$response = $this->oauth->fetch($this->api_url. 'media/'. $root . '/' . ltrim($path, '/'), array(), 'POST');
return json_decode($response['body'],true);
}
/**
* Creates and returns a copy_ref to a file. This reference string can be used to copy that file to another user's Dropbox by passing it in as the from_copy_ref parameter on /fileops/copy.
*
* @param type $path
* @param type $root
* @return type
*/
public function copy_ref($path, $root = null) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$response = $this->oauth->fetch($this->api_url. 'copy_ref/'. $root . '/' . ltrim($path, '/'));
return json_decode($response['body'],true);
}
}
|