API.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. <?php
  2. /**
  3. * Dropbox API class
  4. *
  5. * @package Dropbox
  6. * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
  7. * @author Evert Pot (http://www.rooftopsolutions.nl/)
  8. * @license http://code.google.com/p/dropbox-php/wiki/License MIT
  9. */
  10. class Dropbox_API {
  11. /**
  12. * Sandbox root-path
  13. */
  14. const ROOT_SANDBOX = 'sandbox';
  15. /**
  16. * Dropbox root-path
  17. */
  18. const ROOT_DROPBOX = 'dropbox';
  19. /**
  20. * API URl
  21. */
  22. protected $api_url = 'https://api.dropbox.com/1/';
  23. /**
  24. * Content API URl
  25. */
  26. protected $api_content_url = 'https://api-content.dropbox.com/1/';
  27. /**
  28. * OAuth object
  29. *
  30. * @var Dropbox_OAuth
  31. */
  32. protected $oauth;
  33. /**
  34. * Default root-path, this will most likely be 'sandbox' or 'dropbox'
  35. *
  36. * @var string
  37. */
  38. protected $root;
  39. protected $useSSL;
  40. /**
  41. * PHP is Safe Mode
  42. *
  43. * @var bool
  44. */
  45. private $isSafeMode;
  46. /**
  47. * Chunked file size limit
  48. *
  49. * @var unknown
  50. */
  51. public $chunkSize = 20971520; //20MB
  52. /**
  53. * Constructor
  54. *
  55. * @param Dropbox_OAuth Dropbox_Auth object
  56. * @param string $root default root path (sandbox or dropbox)
  57. */
  58. public function __construct(Dropbox_OAuth $oauth, $root = self::ROOT_DROPBOX, $useSSL = true) {
  59. $this->oauth = $oauth;
  60. $this->root = $root;
  61. $this->useSSL = $useSSL;
  62. $this->isSafeMode = (version_compare(PHP_VERSION, '5.4', '<') && get_cfg_var('safe_mode'));
  63. if (!$this->useSSL)
  64. {
  65. throw new Dropbox_Exception('Dropbox REST API now requires that all requests use SSL');
  66. }
  67. }
  68. /**
  69. * Returns information about the current dropbox account
  70. *
  71. * @return stdclass
  72. */
  73. public function getAccountInfo() {
  74. $data = $this->oauth->fetch($this->api_url . 'account/info');
  75. return json_decode($data['body'],true);
  76. }
  77. /**
  78. * Returns a file's contents
  79. *
  80. * @param string $path path
  81. * @param string $root Use this to override the default root path (sandbox/dropbox)
  82. * @return string
  83. */
  84. public function getFile($path = '', $root = null) {
  85. if (is_null($root)) $root = $this->root;
  86. $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
  87. $result = $this->oauth->fetch($this->api_content_url . 'files/' . $root . '/' . ltrim($path,'/'));
  88. return $result['body'];
  89. }
  90. /**
  91. * Uploads a new file
  92. *
  93. * @param string $path Target path (including filename)
  94. * @param string $file Either a path to a file or a stream resource
  95. * @param string $root Use this to override the default root path (sandbox/dropbox)
  96. * @return bool
  97. */
  98. public function putFile($path, $file, $root = null) {
  99. if (is_resource($file)) {
  100. $stat = fstat($file);
  101. $size = $stat['size'];
  102. } else if (is_string($file) && is_readable($file)) {
  103. $size = filesize($file);
  104. } else {
  105. throw new Dropbox_Exception('File must be a file-resource or a file path string');
  106. }
  107. if ($this->oauth->isPutSupport()) {
  108. if ($size) {
  109. if ($size > $this->chunkSize) {
  110. $res = array('uploadID' => null, 'offset' => 0);
  111. $i[$res['offset']] = 0;
  112. while($i[$res['offset']] < 5) {
  113. $res = $this->chunkedUpload($path, $file, $root, true, $res['offset'], $res['uploadID']);
  114. if (isset($res['uploadID'])) {
  115. if (!isset($i[$res['offset']])) {
  116. $i[$res['offset']] = 0;
  117. } else {
  118. $i[$res['offset']]++;
  119. }
  120. } else {
  121. break;
  122. }
  123. }
  124. return true;
  125. } else {
  126. return $this->putStream($path, $file, $root);
  127. }
  128. }
  129. }
  130. if ($size > 157286400) {
  131. // Dropbox API /files has a maximum file size limit of 150 MB.
  132. // https://www.dropbox.com/developers/core/docs#files-POST
  133. throw new Dropbox_Exception("Uploading file to Dropbox failed");
  134. }
  135. $directory = dirname($path);
  136. $filename = basename($path);
  137. if($directory==='.') $directory = '';
  138. $directory = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($directory));
  139. $filename = str_replace('~', '%7E', rawurlencode($filename));
  140. if (is_null($root)) $root = $this->root;
  141. if (is_string($file)) {
  142. $file = fopen($file,'rb');
  143. } elseif (!is_resource($file)) {
  144. throw new Dropbox_Exception('File must be a file-resource or a file path string');
  145. }
  146. if (!$this->isSafeMode) {
  147. set_time_limit(600);
  148. }
  149. $result=$this->multipartFetch($this->api_content_url . 'files/' .
  150. $root . '/' . trim($directory,'/'), $file, $filename);
  151. if(!isset($result["httpStatus"]) || $result["httpStatus"] != 200)
  152. throw new Dropbox_Exception("Uploading file to Dropbox failed");
  153. return true;
  154. }
  155. /**
  156. * Uploads large files to Dropbox in mulitple chunks
  157. *
  158. * @param string $file Absolute path to the file to be uploaded
  159. * @param string|bool $filename The destination filename of the uploaded file
  160. * @param string $path Path to upload the file to, relative to root
  161. * @param boolean $overwrite Should the file be overwritten? (Default: true)
  162. * @return stdClass
  163. */
  164. public function chunkedUpload($path, $handle, $root = null, $overwrite = true, $offset = 0, $uploadID = null)
  165. {
  166. if (is_string($handle) && is_readable($handle)) {
  167. $handle = fopen($handle, 'rb');
  168. }
  169. if (is_resource($handle)) {
  170. // Seek to the correct position on the file pointer
  171. fseek($handle, $offset);
  172. // Read from the file handle until EOF, uploading each chunk
  173. while ($data = fread($handle, $this->chunkSize)) {
  174. if (!$this->isSafeMode) {
  175. set_time_limit(600);
  176. }
  177. // Open a temporary file handle and write a chunk of data to it
  178. $chunkHandle = fopen('php://temp', 'rwb');
  179. fwrite($chunkHandle, $data);
  180. // Set the file, request parameters and send the request
  181. $this->oauth->setInFile($chunkHandle);
  182. $params = array('upload_id' => $uploadID, 'offset' => $offset);
  183. try {
  184. // Attempt to upload the current chunk
  185. $res = $this->oauth->fetch($this->api_content_url . 'chunked_upload', $params, 'PUT');
  186. $response = json_decode($res['body'], true);
  187. } catch (Exception $e) {
  188. $res = $this->oauth->getLastResponse();
  189. if ($response['httpStatus'] == 400) {
  190. // Incorrect offset supplied, return expected offset and upload ID
  191. $response = json_decode($res['body'], true);
  192. $uploadID = $response['upload_id'];
  193. $offset = $response['offset'];
  194. return array('uploadID' => $uploadID, 'offset' => $offset);
  195. } else {
  196. // Re-throw the caught Exception
  197. throw $e;
  198. }
  199. throw $e;
  200. }
  201. // On subsequent chunks, use the upload ID returned by the previous request
  202. if (isset($response['upload_id'])) {
  203. $uploadID = $response['upload_id'];
  204. }
  205. // Set the data offset
  206. if (isset($response['offset'])) {
  207. $offset = $response['offset'];
  208. }
  209. // Close the file handle for this chunk
  210. fclose($chunkHandle);
  211. }
  212. // Complete the chunked upload
  213. $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
  214. if (is_null($root)) {
  215. $root = $this->root;
  216. }
  217. $params = array('overwrite' => (int) $overwrite, 'upload_id' => $uploadID);
  218. return $this->oauth->fetch($this->api_content_url . 'commit_chunked_upload/' .
  219. $root . '/' . ltrim($path,'/'), $params, 'POST');
  220. } else {
  221. throw new Dropbox_Exception('Could not open ' . $handle . ' for reading');
  222. }
  223. }
  224. /**
  225. * Uploads file data from a stream
  226. *
  227. * Note: This function is experimental and requires further testing
  228. * @param resource $stream A readable stream created using fopen()
  229. * @param string $filename The destination filename, including path
  230. * @param boolean $overwrite Should the file be overwritten? (Default: true)
  231. * @return array
  232. */
  233. public function putStream($path, $file, $root = null, $overwrite = true)
  234. {
  235. if ($this->isSafeMode) {
  236. set_time_limit(600);
  237. }
  238. $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
  239. if (is_null($root)) {
  240. $root = $this->root;
  241. }
  242. $params = array('overwrite' => (int) $overwrite);
  243. $this->oauth->setInfile($file);
  244. $result=$this->oauth->fetch($this->api_content_url . 'files_put/' .
  245. $root . '/' . ltrim($path,'/'), $params, 'PUT');
  246. if (!isset($result["httpStatus"]) || $result["httpStatus"] != 200) {
  247. throw new Dropbox_Exception("Uploading file to Dropbox failed");
  248. }
  249. return true;
  250. }
  251. /**
  252. * Copies a file or directory from one location to another
  253. *
  254. * This method returns the file information of the newly created file.
  255. *
  256. * @param string $from source path
  257. * @param string $to destination path
  258. * @param string $root Use this to override the default root path (sandbox/dropbox)
  259. * @return stdclass
  260. */
  261. public function copy($from, $to, $root = null) {
  262. if (is_null($root)) $root = $this->root;
  263. $response = $this->oauth->fetch($this->api_url . 'fileops/copy', array('from_path' => $from, 'to_path' => $to, 'root' => $root), 'POST');
  264. return json_decode($response['body'],true);
  265. }
  266. /**
  267. * Creates a new folder
  268. *
  269. * This method returns the information from the newly created directory
  270. *
  271. * @param string $path
  272. * @param string $root Use this to override the default root path (sandbox/dropbox)
  273. * @return stdclass
  274. */
  275. public function createFolder($path, $root = null) {
  276. if (is_null($root)) $root = $this->root;
  277. // Making sure the path starts with a /
  278. $path = '/' . ltrim($path,'/');
  279. $response = $this->oauth->fetch($this->api_url . 'fileops/create_folder', array('path' => $path, 'root' => $root),'POST');
  280. return json_decode($response['body'],true);
  281. }
  282. /**
  283. * Deletes a file or folder.
  284. *
  285. * This method will return the metadata information from the deleted file or folder, if successful.
  286. *
  287. * @param string $path Path to new folder
  288. * @param string $root Use this to override the default root path (sandbox/dropbox)
  289. * @return array
  290. */
  291. public function delete($path, $root = null) {
  292. if (is_null($root)) $root = $this->root;
  293. $response = $this->oauth->fetch($this->api_url . 'fileops/delete', array('path' => $path, 'root' => $root), 'POST');
  294. return json_decode($response['body']);
  295. }
  296. /**
  297. * Moves a file or directory to a new location
  298. *
  299. * This method returns the information from the newly created directory
  300. *
  301. * @param mixed $from Source path
  302. * @param mixed $to destination path
  303. * @param string $root Use this to override the default root path (sandbox/dropbox)
  304. * @return stdclass
  305. */
  306. public function move($from, $to, $root = null) {
  307. if (is_null($root)) $root = $this->root;
  308. $response = $this->oauth->fetch($this->api_url . 'fileops/move', array('from_path' => rawurldecode($from), 'to_path' => rawurldecode($to), 'root' => $root), 'POST');
  309. return json_decode($response['body'],true);
  310. }
  311. /**
  312. * Returns file and directory information
  313. *
  314. * @param string $path Path to receive information from
  315. * @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.
  316. * @param string $hash If a hash is supplied, this method simply returns true if nothing has changed since the last request. Good for caching.
  317. * @param int $fileLimit Maximum number of file-information to receive
  318. * @param string $root Use this to override the default root path (sandbox/dropbox)
  319. * @return array|true
  320. */
  321. public function getMetaData($path, $list = true, $hash = null, $fileLimit = null, $root = null) {
  322. if (is_null($root)) $root = $this->root;
  323. $args = array(
  324. 'list' => $list,
  325. );
  326. if (!is_null($hash)) $args['hash'] = $hash;
  327. if (!is_null($fileLimit)) $args['file_limit'] = $fileLimit;
  328. $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
  329. $response = $this->oauth->fetch($this->api_url . 'metadata/' . $root . '/' . ltrim($path,'/'), $args);
  330. /* 304 is not modified */
  331. if ($response['httpStatus']==304) {
  332. return true;
  333. } else {
  334. return json_decode($response['body'],true);
  335. }
  336. }
  337. /**
  338. * 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.
  339. *
  340. * This method returns the information from the newly created directory
  341. *
  342. * @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.
  343. * @return stdclass
  344. */
  345. public function delta($cursor) {
  346. $arg['cursor'] = $cursor;
  347. $response = $this->oauth->fetch($this->api_url . 'delta', $arg, 'POST');
  348. return json_decode($response['body'],true);
  349. }
  350. /**
  351. * Returns a thumbnail (as a string) for a file path.
  352. *
  353. * @param string $path Path to file
  354. * @param string $size small, medium or large
  355. * @param string $root Use this to override the default root path (sandbox/dropbox)
  356. * @return string
  357. */
  358. public function getThumbnail($path, $size = 'small', $root = null) {
  359. if (is_null($root)) $root = $this->root;
  360. $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
  361. $response = $this->oauth->fetch($this->api_content_url . 'thumbnails/' . $root . '/' . ltrim($path,'/'),array('size' => $size));
  362. return $response['body'];
  363. }
  364. /**
  365. * This method is used to generate multipart POST requests for file upload
  366. *
  367. * @param string $uri
  368. * @param array $arguments
  369. * @return bool
  370. */
  371. protected function multipartFetch($uri, $file, $filename) {
  372. /* random string */
  373. $boundary = 'R50hrfBj5JYyfR3vF3wR96GPCC9Fd2q2pVMERvEaOE3D8LZTgLLbRpNwXek3';
  374. $headers = array(
  375. 'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
  376. );
  377. $body="--" . $boundary . "\r\n";
  378. $body.="Content-Disposition: form-data; name=file; filename=".rawurldecode($filename)."\r\n";
  379. $body.="Content-type: application/octet-stream\r\n";
  380. $body.="\r\n";
  381. $body.=stream_get_contents($file);
  382. $body.="\r\n";
  383. $body.="--" . $boundary . "--";
  384. // Dropbox requires the filename to also be part of the regular arguments, so it becomes
  385. // part of the signature.
  386. $uri.='?file=' . $filename;
  387. return $this->oauth->fetch($uri, $body, 'POST', $headers);
  388. }
  389. /**
  390. * Search
  391. *
  392. * Returns metadata for all files and folders that match the search query.
  393. *
  394. * @added by: diszo.sasil
  395. *
  396. * @param string $query
  397. * @param string $root Use this to override the default root path (sandbox/dropbox)
  398. * @param string $path
  399. * @return array
  400. */
  401. public function search($query = '', $root = null, $path = ''){
  402. if (is_null($root)) $root = $this->root;
  403. if(!empty($path)){
  404. $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
  405. }
  406. $response = $this->oauth->fetch($this->api_url . 'search/' . $root . '/' . ltrim($path,'/'),array('query' => $query));
  407. return json_decode($response['body'],true);
  408. }
  409. /**
  410. * Creates and returns a shareable link to files or folders.
  411. *
  412. * Note: Links created by the /shares API call expire after thirty days.
  413. *
  414. * @param string $path
  415. * @param string $root Use this to override the default root path (sandbox/dropbox)
  416. * @param string $short_url When true (default), the URL returned will be shortened using the Dropbox URL shortener
  417. * @return array
  418. */
  419. public function share($path, $root = null, $short_url = true) {
  420. if (is_null($root)) $root = $this->root;
  421. $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
  422. $short_url = ((is_string($short_url) && strtolower($short_url) === 'false') || !$short_url)? 'false' : 'true';
  423. $response = $this->oauth->fetch($this->api_url. 'shares/'. $root . '/' . ltrim($path, '/'), array('short_url' => $short_url), 'POST');
  424. return json_decode($response['body'],true);
  425. }
  426. /**
  427. * Returns a link directly to a file.
  428. * 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.
  429. *
  430. * Note: The /media link expires after four hours, allotting enough time to stream files, but not enough to leave a connection open indefinitely.
  431. *
  432. * @param type $path
  433. * @param type $root
  434. * @return type
  435. */
  436. public function media($path, $root = null) {
  437. if (is_null($root)) $root = $this->root;
  438. $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
  439. $response = $this->oauth->fetch($this->api_url. 'media/'. $root . '/' . ltrim($path, '/'), array(), 'POST');
  440. return json_decode($response['body'],true);
  441. }
  442. /**
  443. * 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.
  444. *
  445. * @param type $path
  446. * @param type $root
  447. * @return type
  448. */
  449. public function copy_ref($path, $root = null) {
  450. if (is_null($root)) $root = $this->root;
  451. $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
  452. $response = $this->oauth->fetch($this->api_url. 'copy_ref/'. $root . '/' . ltrim($path, '/'));
  453. return json_decode($response['body'],true);
  454. }
  455. }