PageRenderTime 33ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/lib/dropbox/Client.php

https://gitlab.com/x33n/platform
PHP | 1350 lines | 506 code | 145 blank | 699 comment | 71 complexity | f46048682c03a0ce35e769b51f16d842 MD5 | raw file
  1. <?php
  2. namespace Dropbox;
  3. /**
  4. * The class used to make most Dropbox API calls. You can use this once you've gotten an
  5. * {@link AccessToken} via {@link WebAuth}.
  6. *
  7. * This class is stateless so it can be shared/reused.
  8. */
  9. class Client
  10. {
  11. /**
  12. * The access token used by this client to make authenticated API calls. You can get an
  13. * access token via {@link WebAuth}.
  14. *
  15. * @return AccessToken
  16. */
  17. function getAccessToken() { return $this->accessToken; }
  18. /** @var AccessToken */
  19. private $accessToken;
  20. /**
  21. * An identifier for the API client, typically of the form "Name/Version".
  22. * This is used to set the HTTP <code>User-Agent</code> header when making API requests.
  23. * Example: <code>"PhotoEditServer/1.3"</code>
  24. *
  25. * If you're the author a higher-level library on top of the basic SDK, and the
  26. * "Photo Edit" app's server code is using your library to access Dropbox, you should append
  27. * your library's name and version to form the full identifier. For example,
  28. * if your library is called "File Picker", you might set this field to:
  29. * <code>"PhotoEditServer/1.3 FilePicker/0.1-beta"</code>
  30. *
  31. * The exact format of the <code>User-Agent</code> header is described in
  32. * <a href="http://tools.ietf.org/html/rfc2616#section-3.8">section 3.8 of the HTTP specification</a>.
  33. *
  34. * Note that underlying HTTP client may append other things to the <code>User-Agent</code>, such as
  35. * the name of the library being used to actually make the HTTP request (such as cURL).
  36. *
  37. * @return string
  38. */
  39. function getClientIdentifier() { return $this->clientIdentifier; }
  40. /** @var string */
  41. private $clientIdentifier;
  42. /**
  43. * The locale of the user of your application. Some API calls return localized
  44. * data and error messages; this "user locale" setting determines which locale
  45. * the server should use to localize those strings.
  46. *
  47. * @return null|string
  48. */
  49. function getUserLocale() { return $this->userLocale; }
  50. /** @var null|string */
  51. private $userLocale;
  52. /**
  53. * The {@link Host} object that determines the hostnames we make requests to.
  54. *
  55. * @return Host
  56. */
  57. function getHost() { return $this->host; }
  58. /**
  59. * Constructor.
  60. *
  61. * @param string $accessToken
  62. * See {@link getAccessToken()}
  63. * @param string $clientIdentifier
  64. * See {@link getClientIdentifier()}
  65. * @param null|string $userLocale
  66. * See {@link getUserLocale()}
  67. */
  68. function __construct($accessToken, $clientIdentifier, $userLocale = null)
  69. {
  70. self::checkAccessTokenArg("accessToken", $accessToken);
  71. self::checkClientIdentifierArg("clientIdentifier", $clientIdentifier);
  72. Checker::argStringNonEmptyOrNull("userLocale", $userLocale);
  73. $this->accessToken = $accessToken;
  74. $this->clientIdentifier = $clientIdentifier;
  75. $this->userLocale = $userLocale;
  76. // The $host parameter is sort of internal. We don't include it in the param list because
  77. // we don't want it to be included in the documentation. Use PHP arg list hacks to get at
  78. // it.
  79. $host = null;
  80. if (\func_num_args() == 4) {
  81. $host = \func_get_arg(3);
  82. Host::checkArgOrNull("host", $host);
  83. }
  84. if ($host === null) {
  85. $host = Host::getDefault();
  86. }
  87. $this->host = $host;
  88. // These fields are redundant, but it makes these values a little more convenient
  89. // to access.
  90. $this->apiHost = $host->getApi();
  91. $this->contentHost = $host->getContent();
  92. }
  93. /** @var string */
  94. private $apiHost;
  95. /** @var string */
  96. private $contentHost;
  97. /**
  98. * Given a <code>$base</code> path for an API endpoint (for example, "/files"), append
  99. * a Dropbox API file path to the end of that URL. Special characters in the file will
  100. * be encoded properly.
  101. *
  102. * This is for endpoints like "/files" takes the path on the URL and not as a separate
  103. * query or POST parameter.
  104. *
  105. * @param string $base
  106. * @param string $path
  107. * @return string
  108. */
  109. function appendFilePath($base, $path)
  110. {
  111. return $base . "/auto/" . rawurlencode(substr($path, 1));
  112. }
  113. /**
  114. * Make an API call to disable the access token that you constructed this <code>Client</code>
  115. * with. After calling this, API calls made with this <code>Client</code> will fail.
  116. *
  117. * See <a href="https://www.dropbox.com/developers/core/docs#disable-token">/disable_access_token</a>.
  118. *
  119. * @throws Exception
  120. */
  121. function disableAccessToken()
  122. {
  123. $response = $this->doPost($this->apiHost, "1/disable_access_token");
  124. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  125. }
  126. /**
  127. * Make an API call to get basic account and quota information.
  128. *
  129. * <code>
  130. * $client = ...
  131. * $accountInfo = $client->getAccountInfo();
  132. * print_r($accountInfo);
  133. * </code>
  134. *
  135. * @return array
  136. * See <a href="https://www.dropbox.com/developers/core/docs#account-info">/account/info</a>.
  137. *
  138. * @throws Exception
  139. */
  140. function getAccountInfo()
  141. {
  142. $response = $this->doGet($this->apiHost, "1/account/info");
  143. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  144. return RequestUtil::parseResponseJson($response->body);
  145. }
  146. /**
  147. * Downloads a file from Dropbox. The file's contents are written to the
  148. * given <code>$outStream</code> and the file's metadata is returned.
  149. *
  150. * <code>
  151. * $client = ...;
  152. * $fd = fopen("./Frog.jpeg", "wb");
  153. * $metadata = $client->getFile("/Photos/Frog.jpeg", $fd);
  154. * fclose($fd);
  155. * print_r($metadata);
  156. * </code>
  157. *
  158. * @param string $path
  159. * The path to the file on Dropbox (UTF-8).
  160. *
  161. * @param resource $outStream
  162. * If the file exists, the file contents will be written to this stream.
  163. *
  164. * @param string|null $rev
  165. * If you want the latest revision of the file at the given path, pass in <code>null</code>.
  166. * If you want a specific version of a file, pass in value of the file metadata's "rev" field.
  167. *
  168. * @return null|array
  169. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata
  170. * object</a> for the file at the given $path and $rev, or <code>null</code> if the file
  171. * doesn't exist,
  172. *
  173. * @throws Exception
  174. */
  175. function getFile($path, $outStream, $rev = null)
  176. {
  177. Path::checkArgNonRoot("path", $path);
  178. Checker::argResource("outStream", $outStream);
  179. Checker::argStringNonEmptyOrNull("rev", $rev);
  180. $url = $this->buildUrlForGetOrPut(
  181. $this->contentHost,
  182. $this->appendFilePath("1/files", $path),
  183. array("rev" => $rev));
  184. $curl = $this->mkCurl($url);
  185. $metadataCatcher = new DropboxMetadataHeaderCatcher($curl->handle);
  186. $streamRelay = new CurlStreamRelay($curl->handle, $outStream);
  187. $response = $curl->exec();
  188. if ($response->statusCode === 404) return null;
  189. if ($response->statusCode !== 200) {
  190. $response->body = $streamRelay->getErrorBody();
  191. throw RequestUtil::unexpectedStatus($response);
  192. }
  193. return $metadataCatcher->getMetadata();
  194. }
  195. /**
  196. * Calling 'uploadFile' with <code>$numBytes</code> less than this value, will cause this SDK
  197. * to use the standard /files_put endpoint. When <code>$numBytes</code> is greater than this
  198. * value, we'll use the /chunked_upload endpoint.
  199. *
  200. * @var int
  201. */
  202. private static $AUTO_CHUNKED_UPLOAD_THRESHOLD = 9863168; // 8 MB
  203. /**
  204. * @var int
  205. */
  206. private static $DEFAULT_CHUNK_SIZE = 4194304; // 4 MB
  207. /**
  208. * Creates a file on Dropbox, using the data from <code>$inStream</code> for the file contents.
  209. *
  210. * <code>
  211. * use \Dropbox as dbx;
  212. * $client = ...;
  213. * $fd = fopen("./frog.jpeg", "rb");
  214. * $md1 = $client->uploadFile("/Photos/Frog.jpeg",
  215. * dbx\WriteMode::add(), $fd);
  216. * fclose($fd);
  217. * print_r($md1);
  218. * $rev = $md1["rev"];
  219. *
  220. * // Re-upload with WriteMode::update(...), which will overwrite the
  221. * // file if it hasn't been modified from our original upload.
  222. * $fd = fopen("./frog-new.jpeg", "rb");
  223. * $md2 = $client->uploadFile("/Photos/Frog.jpeg",
  224. * dbx\WriteMode::update($rev), $fd);
  225. * fclose($fd);
  226. * print_r($md2);
  227. * </code>
  228. *
  229. * @param string $path
  230. * The Dropbox path to save the file to (UTF-8).
  231. *
  232. * @param WriteMode $writeMode
  233. * What to do if there's already a file at the given path.
  234. *
  235. * @param resource $inStream
  236. * The data to use for the file contents.
  237. *
  238. * @param int|null $numBytes
  239. * You can pass in <code>null</code> if you don't know. If you do provide the size, we can
  240. * perform a slightly more efficient upload (fewer network round-trips) for files smaller
  241. * than 8 MB.
  242. *
  243. * @return mixed
  244. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details>metadata
  245. * object</a> for the newly-added file.
  246. *
  247. * @throws Exception
  248. */
  249. function uploadFile($path, $writeMode, $inStream, $numBytes = null)
  250. {
  251. Path::checkArgNonRoot("path", $path);
  252. WriteMode::checkArg("writeMode", $writeMode);
  253. Checker::argResource("inStream", $inStream);
  254. Checker::argNatOrNull("numBytes", $numBytes);
  255. // If we don't know how many bytes are coming, we have to use chunked upload.
  256. // If $numBytes is large, we elect to use chunked upload.
  257. // In all other cases, use regular upload.
  258. if ($numBytes === null || $numBytes > self::$AUTO_CHUNKED_UPLOAD_THRESHOLD) {
  259. $metadata = $this->_uploadFileChunked($path, $writeMode, $inStream, $numBytes,
  260. self::$DEFAULT_CHUNK_SIZE);
  261. } else {
  262. $metadata = $this->_uploadFile($path, $writeMode,
  263. function(Curl $curl) use ($inStream, $numBytes) {
  264. $curl->set(CURLOPT_PUT, true);
  265. $curl->set(CURLOPT_INFILE, $inStream);
  266. $curl->set(CURLOPT_INFILESIZE, $numBytes);
  267. });
  268. }
  269. return $metadata;
  270. }
  271. /**
  272. * Creates a file on Dropbox, using the given $data string as the file contents.
  273. *
  274. * <code>
  275. * use \Dropbox as dbx;
  276. * $client = ...;
  277. * $md = $client->uploadFileFromString("/Grocery List.txt",
  278. * dbx\WriteMode::add(),
  279. * "1. Coke\n2. Popcorn\n3. Toothpaste\n");
  280. * print_r($md);
  281. * </code>
  282. *
  283. * @param string $path
  284. * The Dropbox path to save the file to (UTF-8).
  285. *
  286. * @param WriteMode $writeMode
  287. * What to do if there's already a file at the given path.
  288. *
  289. * @param string $data
  290. * The data to use for the contents of the file.
  291. *
  292. * @return mixed
  293. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details>metadata
  294. * object</a> for the newly-added file.
  295. *
  296. * @throws Exception
  297. */
  298. function uploadFileFromString($path, $writeMode, $data)
  299. {
  300. Path::checkArgNonRoot("path", $path);
  301. WriteMode::checkArg("writeMode", $writeMode);
  302. Checker::argString("data", $data);
  303. return $this->_uploadFile($path, $writeMode, function(Curl $curl) use ($data) {
  304. $curl->set(CURLOPT_CUSTOMREQUEST, "PUT");
  305. $curl->set(CURLOPT_POSTFIELDS, $data);
  306. $curl->addHeader("Content-Type: application/octet-stream");
  307. });
  308. }
  309. /**
  310. * Creates a file on Dropbox, using the data from $inStream as the file contents.
  311. *
  312. * This version of <code>uploadFile</code> splits uploads the file ~4MB chunks at a time and
  313. * will retry a few times if one chunk fails to upload. Uses {@link chunkedUploadStart()},
  314. * {@link chunkedUploadContinue()}, and {@link chunkedUploadFinish()}.
  315. *
  316. * @param string $path
  317. * The Dropbox path to save the file to (UTF-8).
  318. *
  319. * @param WriteMode $writeMode
  320. * What to do if there's already a file at the given path.
  321. *
  322. * @param resource $inStream
  323. * The data to use for the file contents.
  324. *
  325. * @param int|null $numBytes
  326. * The number of bytes available from $inStream.
  327. * You can pass in <code>null</code> if you don't know.
  328. *
  329. * @param int|null $chunkSize
  330. * The number of bytes to upload in each chunk. You can omit this (or pass in
  331. * <code>null</code> and the library will use a reasonable default.
  332. *
  333. * @return mixed
  334. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details>metadata
  335. * object</a> for the newly-added file.
  336. *
  337. * @throws Exception
  338. */
  339. function uploadFileChunked($path, $writeMode, $inStream, $numBytes = null, $chunkSize = null)
  340. {
  341. if ($chunkSize === null) {
  342. $chunkSize = self::$DEFAULT_CHUNK_SIZE;
  343. }
  344. Path::checkArgNonRoot("path", $path);
  345. WriteMode::checkArg("writeMode", $writeMode);
  346. Checker::argResource("inStream", $inStream);
  347. Checker::argNatOrNull("numBytes", $numBytes);
  348. Checker::argIntPositive("chunkSize", $chunkSize);
  349. return $this->_uploadFileChunked($path, $writeMode, $inStream, $numBytes, $chunkSize);
  350. }
  351. /**
  352. * @param string $path
  353. *
  354. * @param WriteMode $writeMode
  355. * What to do if there's already a file at the given path (UTF-8).
  356. *
  357. * @param resource $inStream
  358. * The source of data to upload.
  359. *
  360. * @param int|null $numBytes
  361. * You can pass in <code>null</code>. But if you know how many bytes you expect, pass in
  362. * that value and this function will do a sanity check at the end to make sure the number of
  363. * bytes read from $inStream matches up.
  364. *
  365. * @param int $chunkSize
  366. *
  367. * @return array
  368. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details>metadata
  369. * object</a> for the newly-added file.
  370. */
  371. private function _uploadFileChunked($path, $writeMode, $inStream, $numBytes, $chunkSize)
  372. {
  373. Path::checkArg("path", $path);
  374. WriteMode::checkArg("writeMode", $writeMode);
  375. Checker::argResource("inStream", $inStream);
  376. Checker::argNatOrNull("numBytes", $numBytes);
  377. Checker::argNat("chunkSize", $chunkSize);
  378. // NOTE: This function performs 3 retries on every call. This is maybe not the right
  379. // layer to make retry decisions. It's also awkward because none of the other calls
  380. // perform retries.
  381. assert($chunkSize > 0);
  382. $data = self::readFully($inStream, $chunkSize);
  383. $len = strlen($data);
  384. $client = $this;
  385. $uploadId = RequestUtil::runWithRetry(3, function() use ($data, $client) {
  386. return $client->chunkedUploadStart($data);
  387. });
  388. $byteOffset = $len;
  389. while (!feof($inStream)) {
  390. $data = self::readFully($inStream, $chunkSize);
  391. $len = strlen($data);
  392. while (true) {
  393. $r = RequestUtil::runWithRetry(3,
  394. function() use ($client, $uploadId, $byteOffset, $data) {
  395. return $client->chunkedUploadContinue($uploadId, $byteOffset, $data);
  396. });
  397. if ($r === true) { // Chunk got uploaded!
  398. $byteOffset += $len;
  399. break;
  400. }
  401. if ($r === false) { // Server didn't recognize our upload ID
  402. // This is very unlikely since we're uploading all the chunks in sequence.
  403. throw new Exception_BadResponse("Server forgot our uploadId");
  404. }
  405. // Otherwise, the server is at a different byte offset from us.
  406. $serverByteOffset = $r;
  407. assert($serverByteOffset !== $byteOffset); // chunkedUploadContinue ensures this.
  408. // An earlier byte offset means the server has lost data we sent earlier.
  409. if ($serverByteOffset < $byteOffset) throw new Exception_BadResponse(
  410. "Server is at an ealier byte offset: us=$byteOffset, server=$serverByteOffset");
  411. $diff = $serverByteOffset - $byteOffset;
  412. // If the server is past where we think it could possibly be, something went wrong.
  413. if ($diff > $len) throw new Exception_BadResponse(
  414. "Server is more than a chunk ahead: us=$byteOffset, server=$serverByteOffset");
  415. // The normal case is that the server is a bit further along than us because of a
  416. // partially-uploaded chunk. Finish it off.
  417. $byteOffset += $diff;
  418. if ($diff === $len) break; // If the server is at the end, we're done.
  419. $data = substr($data, $diff);
  420. }
  421. }
  422. if ($numBytes !== null && $byteOffset !== $numBytes) throw new \InvalidArgumentException(
  423. "You passed numBytes=$numBytes but the stream had $byteOffset bytes.");
  424. $metadata = RequestUtil::runWithRetry(3,
  425. function() use ($client, $uploadId, $path, $writeMode) {
  426. return $client->chunkedUploadFinish($uploadId, $path, $writeMode);
  427. });
  428. return $metadata;
  429. }
  430. /**
  431. * Sometimes fread() returns less than the request number of bytes (for example, when reading
  432. * from network streams). This function repeatedly calls fread until the requested number of
  433. * bytes have been read or we've reached EOF.
  434. *
  435. * @param resource $inStream
  436. * @param int $numBytes
  437. * @throws StreamReadException
  438. * @return string
  439. */
  440. private static function readFully($inStream, $numBytes)
  441. {
  442. Checker::argNat("numBytes", $numBytes);
  443. $full = '';
  444. $bytesRemaining = $numBytes;
  445. while (!feof($inStream) && $bytesRemaining > 0) {
  446. $part = fread($inStream, $bytesRemaining);
  447. if ($part === false) throw new StreamReadException("Error reading from \$inStream.");
  448. $full .= $part;
  449. $bytesRemaining -= strlen($part);
  450. }
  451. return $full;
  452. }
  453. /**
  454. * @param string $path
  455. * @param WriteMode $writeMode
  456. * @param callable $curlConfigClosure
  457. * @return array
  458. */
  459. private function _uploadFile($path, $writeMode, $curlConfigClosure)
  460. {
  461. Path::checkArg("path", $path);
  462. WriteMode::checkArg("writeMode", $writeMode);
  463. Checker::argCallable("curlConfigClosure", $curlConfigClosure);
  464. $url = $this->buildUrlForGetOrPut(
  465. $this->contentHost,
  466. $this->appendFilePath("1/files_put", $path),
  467. $writeMode->getExtraParams());
  468. $curl = $this->mkCurl($url);
  469. $curlConfigClosure($curl);
  470. $curl->set(CURLOPT_RETURNTRANSFER, true);
  471. $response = $curl->exec();
  472. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  473. return RequestUtil::parseResponseJson($response->body);
  474. }
  475. /**
  476. * Start a new chunked upload session and upload the first chunk of data.
  477. *
  478. * @param string $data
  479. * The data to start off the chunked upload session.
  480. *
  481. * @return array
  482. * A pair of <code>(string $uploadId, int $byteOffset)</code>. <code>$uploadId</code>
  483. * is a unique identifier for this chunked upload session. You pass this in to
  484. * {@link chunkedUploadContinue} and {@link chuunkedUploadFinish}. <code>$byteOffset</code>
  485. * is the number of bytes that were successfully uploaded.
  486. *
  487. * @throws Exception
  488. */
  489. function chunkedUploadStart($data)
  490. {
  491. Checker::argString("data", $data);
  492. $response = $this->_chunkedUpload(array(), $data);
  493. if ($response->statusCode === 404) {
  494. throw new Exception_BadResponse("Got a 404, but we didn't send up an 'upload_id'");
  495. }
  496. $correction = self::_chunkedUploadCheckForOffsetCorrection($response);
  497. if ($correction !== null) throw new Exception_BadResponse(
  498. "Got an offset-correcting 400 response, but we didn't send an offset");
  499. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  500. list($uploadId, $byteOffset) = self::_chunkedUploadParse200Response($response->body);
  501. $len = strlen($data);
  502. if ($byteOffset !== $len) throw new Exception_BadResponse(
  503. "We sent $len bytes, but server returned an offset of $byteOffset");
  504. return $uploadId;
  505. }
  506. /**
  507. * Append another chunk data to a previously-started chunked upload session.
  508. *
  509. * @param string $uploadId
  510. * The unique identifier for the chunked upload session. This is obtained via
  511. * {@link chunkedUploadStart}.
  512. *
  513. * @param int $byteOffset
  514. * The number of bytes you think you've already uploaded to the given chunked upload
  515. * session. The server will append the new chunk of data after that point.
  516. *
  517. * @param string $data
  518. * The data to append to the existing chunked upload session.
  519. *
  520. * @return int|bool
  521. * If <code>false</code>, it means the server didn't know about the given
  522. * <code>$uploadId</code>. This may be because the chunked upload session has expired
  523. * (they last around 24 hours).
  524. * If <code>true</code>, the chunk was successfully uploaded. If an integer, it means
  525. * you and the server don't agree on the current <code>$byteOffset</code>. The returned
  526. * integer is the server's internal byte offset for the chunked upload session. You need
  527. * to adjust your input to match.
  528. *
  529. * @throws Exception
  530. */
  531. function chunkedUploadContinue($uploadId, $byteOffset, $data)
  532. {
  533. Checker::argStringNonEmpty("uploadId", $uploadId);
  534. Checker::argNat("byteOffset", $byteOffset);
  535. Checker::argString("data", $data);
  536. $response = $this->_chunkedUpload(
  537. array("upload_id" => $uploadId, "offset" => $byteOffset), $data);
  538. if ($response->statusCode === 404) {
  539. // The server doesn't know our upload ID. Maybe it expired?
  540. return false;
  541. }
  542. $correction = self::_chunkedUploadCheckForOffsetCorrection($response);
  543. if ($correction !== null) {
  544. list($correctedUploadId, $correctedByteOffset) = $correction;
  545. if ($correctedUploadId !== $uploadId) throw new Exception_BadResponse(
  546. "Corrective 400 upload_id mismatch: us=".
  547. Util::q($uploadId)." server=".Util::q($correctedUploadId));
  548. if ($correctedByteOffset === $byteOffset) throw new Exception_BadResponse(
  549. "Corrective 400 offset is the same as ours: $byteOffset");
  550. return $correctedByteOffset;
  551. }
  552. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  553. list($retUploadId, $retByteOffset) = self::_chunkedUploadParse200Response($response->body);
  554. $nextByteOffset = $byteOffset + strlen($data);
  555. if ($uploadId !== $retUploadId) throw new Exception_BadResponse(
  556. "upload_id mismatch: us=".Util::q($uploadId) .", server=".Util::q($uploadId));
  557. if ($nextByteOffset !== $retByteOffset) throw new Exception_BadResponse(
  558. "next-offset mismatch: us=$nextByteOffset, server=$retByteOffset");
  559. return true;
  560. }
  561. /**
  562. * @param string $body
  563. * @return array
  564. */
  565. private static function _chunkedUploadParse200Response($body)
  566. {
  567. $j = RequestUtil::parseResponseJson($body);
  568. $uploadId = self::getField($j, "upload_id");
  569. $byteOffset = self::getField($j, "offset");
  570. return array($uploadId, $byteOffset);
  571. }
  572. /**
  573. * @param HttpResponse $response
  574. * @return array|null
  575. */
  576. private static function _chunkedUploadCheckForOffsetCorrection($response)
  577. {
  578. if ($response->statusCode !== 400) return null;
  579. $j = json_decode($response->body, true, 10);
  580. if ($j === null) return null;
  581. if (!array_key_exists("upload_id", $j) || !array_key_exists("offset", $j)) return null;
  582. $uploadId = $j["upload_id"];
  583. $byteOffset = $j["offset"];
  584. return array($uploadId, $byteOffset);
  585. }
  586. /**
  587. * Creates a file on Dropbox using the accumulated contents of the given chunked upload session.
  588. *
  589. * See <a href="https://www.dropbox.com/developers/core/docs#commit-chunked-upload">/commit_chunked_upload</a>.
  590. *
  591. * @param string $uploadId
  592. * The unique identifier for the chunked upload session. This is obtained via
  593. * {@link chunkedUploadStart}.
  594. *
  595. * @param string $path
  596. * The Dropbox path to save the file to ($path).
  597. *
  598. * @param WriteMode $writeMode
  599. * What to do if there's already a file at the given path.
  600. *
  601. * @return array|null
  602. * If <code>null</code>, it means the Dropbox server wasn't aware of the
  603. * <code>$uploadId</code> you gave it.
  604. * Otherwise, you get back the
  605. * <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata object</a>
  606. * for the newly-created file.
  607. *
  608. * @throws Exception
  609. */
  610. function chunkedUploadFinish($uploadId, $path, $writeMode)
  611. {
  612. Checker::argStringNonEmpty("uploadId", $uploadId);
  613. Path::checkArgNonRoot("path", $path);
  614. WriteMode::checkArg("writeMode", $writeMode);
  615. $params = array_merge(array("upload_id" => $uploadId), $writeMode->getExtraParams());
  616. $response = $this->doPost(
  617. $this->contentHost,
  618. $this->appendFilePath("1/commit_chunked_upload", $path),
  619. $params);
  620. if ($response->statusCode === 404) return null;
  621. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  622. return RequestUtil::parseResponseJson($response->body);
  623. }
  624. /**
  625. * @param array $params
  626. * @param string $data
  627. * @return HttpResponse
  628. */
  629. protected function _chunkedUpload($params, $data)
  630. // Marked 'protected' so I can override it in testing.
  631. {
  632. $url = $this->buildUrlForGetOrPut(
  633. $this->contentHost, "1/chunked_upload", $params);
  634. $curl = $this->mkCurl($url);
  635. // We can't use CURLOPT_PUT because it wants a stream, but we already have $data in memory.
  636. $curl->set(CURLOPT_CUSTOMREQUEST, "PUT");
  637. $curl->set(CURLOPT_POSTFIELDS, $data);
  638. $curl->addHeader("Content-Type: application/octet-stream");
  639. $curl->set(CURLOPT_RETURNTRANSFER, true);
  640. return $curl->exec();
  641. }
  642. /**
  643. * Returns the metadata for whatever file or folder is at the given path.
  644. *
  645. * <code>
  646. * $client = ...;
  647. * $md = $client->getMetadata("/Photos/Frog.jpeg");
  648. * print_r($md);
  649. * </code>
  650. *
  651. * @param string $path
  652. * The Dropbox path to a file or folder (UTF-8).
  653. *
  654. * @return array|null
  655. * If there is a file or folder at the given path, you'll get back the
  656. * <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata object</a>
  657. * for that file or folder. If not, you'll get back <code>null</code>.
  658. *
  659. * @throws Exception
  660. */
  661. function getMetadata($path)
  662. {
  663. Path::checkArg("path", $path);
  664. return $this->_getMetadata($path, array("list" => "false"));
  665. }
  666. /**
  667. * Returns the metadata for whatever file or folder is at the given path and, if it's a folder,
  668. * also include the metadata for all the immediate children of that folder.
  669. *
  670. * <code>
  671. * $client = ...;
  672. * $md = $client->getMetadataWithChildren("/Photos");
  673. * print_r($md);
  674. * </code>
  675. *
  676. * @param string $path
  677. * The Dropbox path to a file or folder (UTF-8).
  678. *
  679. * @return array|null
  680. * If there is a file or folder at the given path, you'll get back the
  681. * <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata object</a>
  682. * for that file or folder, along with all immediate children if it's a folder. If not,
  683. * you'll get back <code>null</code>.
  684. *
  685. * @throws Exception
  686. */
  687. function getMetadataWithChildren($path)
  688. {
  689. Path::checkArg("path", $path);
  690. return $this->_getMetadata($path, array("list" => "true", "file_limit" => "25000"));
  691. }
  692. /**
  693. * @param string $path
  694. * @param array $params
  695. * @return array
  696. */
  697. private function _getMetadata($path, $params)
  698. {
  699. $response = $this->doGet(
  700. $this->apiHost,
  701. $this->appendFilePath("1/metadata", $path),
  702. $params);
  703. if ($response->statusCode === 404) return null;
  704. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  705. $metadata = RequestUtil::parseResponseJson($response->body);
  706. if (array_key_exists("is_deleted", $metadata) && $metadata["is_deleted"]) return null;
  707. return $metadata;
  708. }
  709. /**
  710. * If you've previously retrieved the metadata for a folder and its children, this method will
  711. * retrieve updated metadata only if something has changed. This is more efficient than
  712. * calling {@link getMetadataWithChildren} if you have a cache of previous results.
  713. *
  714. * <code>
  715. * $client = ...;
  716. * $md = $client->getMetadataWithChildren("/Photos");
  717. * print_r($md);
  718. * assert($md["is_dir"], "expecting \"/Photos\" to be a folder");
  719. *
  720. * sleep(10);
  721. *
  722. * // Now see if anything changed...
  723. * list($changed, $new_md) = $client->getMetadataWithChildrenIfChanged(
  724. * "/Photos", $md["hash"]);
  725. * if ($changed) {
  726. * echo "Folder changed.\n";
  727. * print_r($new_md);
  728. * } else {
  729. * echo "Folder didn't change.\n";
  730. * }
  731. * </code>
  732. *
  733. * @param string $path
  734. * The Dropbox path to a folder (UTF-8).
  735. *
  736. * @param string $previousFolderHash
  737. * The "hash" field from the previously retrieved folder metadata.
  738. *
  739. * @return array
  740. * A <code>list(boolean $changed, array $metadata)</code>. If the metadata hasn't changed,
  741. * you'll get <code>list(false, null)</code>. If the metadata of the folder or any of its
  742. * children has changed, you'll get <code>list(true, $newMetadata)</code>. $metadata is a
  743. * <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata object</a>.
  744. *
  745. * @throws Exception
  746. */
  747. function getMetadataWithChildrenIfChanged($path, $previousFolderHash)
  748. {
  749. Path::checkArg("path", $path);
  750. Checker::argStringNonEmpty("previousFolderHash", $previousFolderHash);
  751. $params = array("list" => "true", "file_limit" => "25000", "hash" => $previousFolderHash);
  752. $response = $this->doGet(
  753. $this->apiHost,
  754. $this->appendFilePath("1/metadata", $path),
  755. $params);
  756. if ($response->statusCode === 304) return array(false, null);
  757. if ($response->statusCode === 404) return array(true, null);
  758. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  759. $metadata = RequestUtil::parseResponseJson($response->body);
  760. if (array_key_exists("is_deleted", $metadata) && $metadata["is_deleted"]) {
  761. return array(true, null);
  762. }
  763. return array(true, $metadata);
  764. }
  765. /**
  766. * A way of letting you keep up with changes to files and folders in a user's Dropbox.
  767. *
  768. * @param string|null $cursor
  769. * If this is the first time you're calling this, pass in <code>null</code>. Otherwise,
  770. * pass in whatever cursor was returned by the previous call.
  771. *
  772. * @param string|null $pathPrefix
  773. * If <code>null</code>, you'll get results for the entire folder (either the user's
  774. * entire Dropbox or your App Folder). If you set <code>$path_prefix</code> to
  775. * "/Photos/Vacation", you'll only get results for that path and any files and folders
  776. * under it.
  777. *
  778. * @return array
  779. * A <a href="https://www.dropbox.com/developers/core/docs#delta">delta page</a>, which
  780. * contains a list of changes to apply along with a new "cursor" that should be passed into
  781. * future <code>getDelta</code> calls. If the "reset" field is <code>true</code>, you
  782. * should clear your local state before applying the changes. If the "has_more" field is
  783. * <code>true</code>, call <code>getDelta</code> immediately to get more results, otherwise
  784. * wait a while (at least 5 minutes) before calling <code>getDelta</code> again.
  785. *
  786. * @throws Exception
  787. */
  788. function getDelta($cursor = null, $pathPrefix = null)
  789. {
  790. Checker::argStringNonEmptyOrNull("cursor", $cursor);
  791. Path::checkArgOrNull("pathPrefix", $pathPrefix);
  792. $response = $this->doPost($this->apiHost, "1/delta", array(
  793. "cursor" => $cursor,
  794. "path_prefix" => $pathPrefix));
  795. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  796. return RequestUtil::parseResponseJson($response->body);
  797. }
  798. /**
  799. * Gets the metadata for all the file revisions (up to a limit) for a given path.
  800. *
  801. * See <a href="https://www.dropbox.com/developers/core/docs#revisions">/revisions</a>.
  802. *
  803. * @param string path
  804. * The Dropbox path that you want file revision metadata for (UTF-8).
  805. *
  806. * @param int|null limit
  807. * The maximum number of revisions to return.
  808. *
  809. * @return array|null
  810. * A list of <a href="https://www.dropbox.com/developers/core/docs#metadata-details>metadata
  811. * objects</a>, one for each file revision. The later revisions appear first in the list.
  812. * If <code>null</code>, then there were too many revisions at that path.
  813. *
  814. * @throws Exception
  815. */
  816. function getRevisions($path, $limit = null)
  817. {
  818. Path::checkArgNonRoot("path", $path);
  819. Checker::argIntPositiveOrNull("limit", $limit);
  820. $response = $this->doGet(
  821. $this->apiHost,
  822. $this->appendFilePath("1/revisions", $path),
  823. array("rev_limit" => $limit));
  824. if ($response->statusCode === 406) return null;
  825. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  826. return RequestUtil::parseResponseJson($response->body);
  827. }
  828. /**
  829. * Takes a copy of the file at the given revision and saves it over the current copy. This
  830. * will create a new revision, but the file contents will match the revision you specified.
  831. *
  832. * See <a href="https://www.dropbox.com/developers/core/docs#restore">/restore</a>.
  833. *
  834. * @param string $path
  835. * The Dropbox path of the file to restore (UTF-8).
  836. *
  837. * @param string $rev
  838. * The revision to restore the contents to.
  839. *
  840. * @return mixed
  841. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata
  842. * object</a>
  843. *
  844. * @throws Exception
  845. */
  846. function restoreFile($path, $rev)
  847. {
  848. Path::checkArgNonRoot("path", $path);
  849. Checker::argStringNonEmpty("rev", $rev);
  850. $response = $this->doPost(
  851. $this->apiHost,
  852. $this->appendFilePath("1/restore", $path),
  853. array("rev" => $rev));
  854. if ($response->statusCode === 404) return null;
  855. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  856. return RequestUtil::parseResponseJson($response->body);
  857. }
  858. /**
  859. * Returns metadata for all files and folders whose filename matches the query string.
  860. *
  861. * See <a href="https://www.dropbox.com/developers/core/docs#search">/search</a>.
  862. *
  863. * @param string $basePath
  864. * The path to limit the search to (UTF-8). Pass in "/" to search everything.
  865. *
  866. * @param string $query
  867. * A space-separated list of substrings to search for. A file matches only if it contains
  868. * all the substrings.
  869. *
  870. * @param int|null $limit
  871. * The maximum number of results to return.
  872. *
  873. * @param bool $includeDeleted
  874. * Whether to include deleted files in the results.
  875. *
  876. * @return mixed
  877. * A list of <a href="https://www.dropbox.com/developers/core/docs#metadata-details>metadata
  878. * objects</a> of files that match the search query.
  879. *
  880. * @throws Exception
  881. */
  882. function searchFileNames($basePath, $query, $limit = null, $includeDeleted = false)
  883. {
  884. Path::checkArg("basePath", $basePath);
  885. Checker::argStringNonEmpty("query", $query);
  886. Checker::argNatOrNull("limit", $limit);
  887. Checker::argBool("includeDeleted", $includeDeleted);
  888. $response = $this->doPost(
  889. $this->apiHost,
  890. $this->appendFilePath("1/search", $basePath),
  891. array(
  892. "query" => $query,
  893. "file_limit" => $limit,
  894. "include_deleted" => $includeDeleted,
  895. ));
  896. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  897. return RequestUtil::parseResponseJson($response->body);
  898. }
  899. /**
  900. * Creates and returns a public link to a file or folder's "preview page". This link can be
  901. * used without authentication. The preview page may contain a thumbnail or some other
  902. * preview of the file, along with a download link to download the actual file.
  903. *
  904. * See <a href="https://www.dropbox.com/developers/core/docs#shares">/shares</a>.
  905. *
  906. * @param string $path
  907. * The Dropbox path to the file or folder you want to create a shareable link to (UTF-8).
  908. *
  909. * @return string
  910. * The URL of the preview page.
  911. *
  912. * @throws Exception
  913. */
  914. function createShareableLink($path)
  915. {
  916. Path::checkArg("path", $path);
  917. $response = $this->doPost(
  918. $this->apiHost,
  919. $this->appendFilePath("1/shares", $path),
  920. array(
  921. "short_url" => "false",
  922. ));
  923. if ($response->statusCode === 404) return null;
  924. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  925. $j = RequestUtil::parseResponseJson($response->body);
  926. return self::getField($j, "url");
  927. }
  928. /**
  929. * Creates and returns a direct link to a file. This link can be used without authentication.
  930. * This link will expire in a few hours.
  931. *
  932. * See <a href="https://www.dropbox.com/developers/core/docs#media">/media</a>.
  933. *
  934. * @param string $path
  935. * The Dropbox path to a file or folder (UTF-8).
  936. *
  937. * @return array
  938. * A <code>list(string $url, \DateTime $expires)</code> where <code>$url</code> is a direct
  939. * link to the requested file and <code>$expires</code> is a standard PHP
  940. * <code>\DateTime</code> representing when <code>$url</code> will stop working.
  941. *
  942. * @throws Exception
  943. */
  944. function createTemporaryDirectLink($path)
  945. {
  946. Path::checkArgNonRoot("path", $path);
  947. $response = $this->doPost(
  948. $this->apiHost,
  949. $this->appendFilePath("1/media", $path));
  950. if ($response->statusCode === 404) return null;
  951. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  952. $j = RequestUtil::parseResponseJson($response->body);
  953. $url = self::getField($j, "url");
  954. $expires = self::parseDateTime(self::getField($j, "expires"));
  955. return array($url, $expires);
  956. }
  957. /**
  958. * Creates and returns a "copy ref" to a file. A copy ref can be used to copy a file across
  959. * different Dropbox accounts without downloading and re-uploading.
  960. *
  961. * For example: Create a <code>Client</code> using the access token from one account and call
  962. * <code>createCopyRef</code>. Then, create a <code>Client</code> using the access token for
  963. * another account and call <code>copyFromCopyRef</code> using the copy ref. (You need to use
  964. * the same app key both times.)
  965. *
  966. * See <a href="https://www.dropbox.com/developers/core/docs#copy_ref">/copy_ref</a>.
  967. *
  968. * @param string path
  969. * The Dropbox path of the file or folder you want to create a copy ref for (UTF-8).
  970. *
  971. * @return string
  972. * The copy ref (just a string that you keep track of).
  973. *
  974. * @throws Exception
  975. */
  976. function createCopyRef($path)
  977. {
  978. Path::checkArg("path", $path);
  979. $response = $this->doGet(
  980. $this->apiHost,
  981. $this->appendFilePath("1/copy_ref", $path));
  982. if ($response->statusCode === 404) return null;
  983. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  984. $j = RequestUtil::parseResponseJson($response->body);
  985. return self::getField($j, "copy_ref");
  986. }
  987. /**
  988. * Gets a thumbnail image representation of the file at the given path.
  989. *
  990. * See <a href="https://www.dropbox.com/developers/core/docs#thumbnails">/thumbnails</a>.
  991. *
  992. * @param string $path
  993. * The path to the file you want a thumbnail for (UTF-8).
  994. *
  995. * @param string $format
  996. * One of the two image formats: "jpeg" or "png".
  997. *
  998. * @param string $size
  999. * One of the predefined image size names, as a string:
  1000. * <ul>
  1001. * <li>"xs" - 32x32</li>
  1002. * <li>"s" - 64x64</li>
  1003. * <li>"m" - 128x128</li>
  1004. * <li>"l" - 640x480</li>
  1005. * <li>"xl" - 1024x768</li>
  1006. * </ul>
  1007. *
  1008. * @return array|null
  1009. * If the file exists, you'll get <code>list(array $metadata, string $data)</code> where
  1010. * <code>$metadata</code> is the file's
  1011. * <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata object</a>
  1012. * and $data is the raw data for the thumbnail image. If the file doesn't exist, you'll
  1013. * get <code>null</code>.
  1014. *
  1015. * @throws Exception
  1016. */
  1017. function getThumbnail($path, $format, $size)
  1018. {
  1019. Path::checkArgNonRoot("path", $path);
  1020. Checker::argString("format", $format);
  1021. Checker::argString("size", $size);
  1022. if (!in_array($format, array("jpeg", "png"))) {
  1023. throw new \InvalidArgumentException("Invalid 'format': ".Util::q($format));
  1024. }
  1025. if (!in_array($size, array("xs", "s", "m", "l", "xl"))) {
  1026. throw new \InvalidArgumentException("Invalid 'size': ".Util::q($format));
  1027. }
  1028. $url = $this->buildUrlForGetOrPut(
  1029. $this->contentHost,
  1030. $this->appendFilePath("1/thumbnails", $path),
  1031. array("size" => $size, "format" => $format));
  1032. $curl = $this->mkCurl($url);
  1033. $metadataCatcher = new DropboxMetadataHeaderCatcher($curl->handle);
  1034. $curl->set(CURLOPT_RETURNTRANSFER, true);
  1035. $response = $curl->exec();
  1036. if ($response->statusCode === 404) return null;
  1037. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  1038. $metadata = $metadataCatcher->getMetadata();
  1039. return array($metadata, $response->body);
  1040. }
  1041. /**
  1042. * Copies a file or folder to a new location
  1043. *
  1044. * See <a href="https://www.dropbox.com/developers/core/docs#fileops-copy">/fileops/copy</a>.
  1045. *
  1046. * @param string $fromPath
  1047. * The Dropbox path of the file or folder you want to copy (UTF-8).
  1048. *
  1049. * @param string $toPath
  1050. * The destination Dropbox path (UTF-8).
  1051. *
  1052. * @return mixed
  1053. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata
  1054. * object</a> for the new file or folder.
  1055. *
  1056. * @throws Exception
  1057. */
  1058. function copy($fromPath, $toPath)
  1059. {
  1060. Path::checkArg("fromPath", $fromPath);
  1061. Path::checkArgNonRoot("toPath", $toPath);
  1062. $response = $this->doPost(
  1063. $this->apiHost,
  1064. "1/fileops/copy",
  1065. array(
  1066. "root" => "auto",
  1067. "from_path" => $fromPath,
  1068. "to_path" => $toPath,
  1069. ));
  1070. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  1071. return RequestUtil::parseResponseJson($response->body);
  1072. }
  1073. /**
  1074. * Creates a file or folder based on an existing copy ref (possibly from a different Dropbox
  1075. * account).
  1076. *
  1077. * See <a href="https://www.dropbox.com/developers/core/docs#fileops-copy">/fileops/copy</a>.
  1078. *
  1079. * @param string $copyRef
  1080. * A copy ref obtained via the {@link createCopyRef()} call.
  1081. *
  1082. * @param string $toPath
  1083. * The Dropbox path you want to copy the file or folder to (UTF-8).
  1084. *
  1085. * @return mixed
  1086. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata
  1087. * object</a> for the new file or folder.
  1088. *
  1089. * @throws Exception
  1090. */
  1091. function copyFromCopyRef($copyRef, $toPath)
  1092. {
  1093. Checker::argStringNonEmpty("copyRef", $copyRef);
  1094. Path::checkArgNonRoot("toPath", $toPath);
  1095. $response = $this->doPost(
  1096. $this->apiHost,
  1097. "1/fileops/copy",
  1098. array(
  1099. "root" => "auto",
  1100. "from_copy_ref" => $copyRef,
  1101. "to_path" => $toPath,
  1102. )
  1103. );
  1104. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  1105. return RequestUtil::parseResponseJson($response->body);
  1106. }
  1107. /**
  1108. * Creates a folder.
  1109. *
  1110. * See <a href="https://www.dropbox.com/developers/core/docs#fileops-create-folder">/fileops/create_folder</a>.
  1111. *
  1112. * @param string $path
  1113. * The Dropbox path at which to create the folder (UTF-8).
  1114. *
  1115. * @return array|null
  1116. * If successful, you'll get back the
  1117. * <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata object</a>
  1118. * for the newly-created folder. If not successful, you'll get <code>null</code>.
  1119. *
  1120. * @throws Exception
  1121. */
  1122. function createFolder($path)
  1123. {
  1124. Path::checkArgNonRoot("path", $path);
  1125. $response = $this->doPost(
  1126. $this->apiHost,
  1127. "1/fileops/create_folder",
  1128. array(
  1129. "root" => "auto",
  1130. "path" => $path,
  1131. ));
  1132. if ($response->statusCode === 403) return null;
  1133. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  1134. return RequestUtil::parseResponseJson($response->body);
  1135. }
  1136. /**
  1137. * Deletes a file or folder
  1138. *
  1139. * See <a href="https://www.dropbox.com/developers/core/docs#fileops-delete">/fileops/delete</a>.
  1140. *
  1141. * @param string $path
  1142. * The Dropbox path of the file or folder to delete (UTF-8).
  1143. *
  1144. * @return mixed
  1145. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata
  1146. * object</a> for the deleted file or folder.
  1147. *
  1148. * @throws Exception
  1149. */
  1150. function delete($path)
  1151. {
  1152. Path::checkArgNonRoot("path", $path);
  1153. $response = $this->doPost(
  1154. $this->apiHost,
  1155. "1/fileops/delete",
  1156. array(
  1157. "root" => "auto",
  1158. "path" => $path,
  1159. ));
  1160. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  1161. return RequestUtil::parseResponseJson($response->body);
  1162. }
  1163. /**
  1164. * Moves a file or folder to a new location.
  1165. *
  1166. * See <a href="https://www.dropbox.com/developers/core/docs#fileops-move">/fileops/move</a>.
  1167. *
  1168. * @param string $fromPath
  1169. * The source Dropbox path (UTF-8).
  1170. *
  1171. * @param string $toPath
  1172. * The destination Dropbox path (UTF-8).
  1173. *
  1174. * @return mixed
  1175. * The <a href="https://www.dropbox.com/developers/core/docs#metadata-details">metadata
  1176. * object</a> for the destination file or folder.
  1177. *
  1178. * @throws Exception
  1179. */
  1180. function move($fromPath, $toPath)
  1181. {
  1182. Path::checkArgNonRoot("fromPath", $fromPath);
  1183. Path::checkArgNonRoot("toPath", $toPath);
  1184. $response = $this->doPost(
  1185. $this->apiHost,
  1186. "1/fileops/move",
  1187. array(
  1188. "root" => "auto",
  1189. "from_path" => $fromPath,
  1190. "to_path" => $toPath,
  1191. ));
  1192. if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
  1193. return RequestUtil::parseResponseJson($response->body);
  1194. }
  1195. /**
  1196. * Build a URL for making a GET or PUT request. Will add the "locale"
  1197. * parameter.
  1198. *
  1199. * @param string $host
  1200. * Either the "API" or "API content" hostname from {@link getHost()}.
  1201. * @param string $path
  1202. * The "path" part of the URL. For example, "/account/info".
  1203. * @param array|null $params
  1204. * URL parameters. For