DAV.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Carlos Cerrillo <ccerrillo@gmail.com>
  8. * @author Felix Moeller <mail@felixmoeller.de>
  9. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Philipp Kapfer <philipp.kapfer@gmx.at>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Thomas Müller <thomas.mueller@tmit.eu>
  16. * @author Vincent Petry <pvince81@owncloud.com>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OC\Files\Storage;
  34. use Exception;
  35. use GuzzleHttp\Exception\RequestException;
  36. use GuzzleHttp\Message\ResponseInterface;
  37. use OC\Files\Filesystem;
  38. use OC\Files\Stream\Close;
  39. use Icewind\Streams\IteratorDirectory;
  40. use OC\MemCache\ArrayCache;
  41. use OCP\AppFramework\Http;
  42. use OCP\Constants;
  43. use OCP\Files;
  44. use OCP\Files\FileInfo;
  45. use OCP\Files\StorageInvalidException;
  46. use OCP\Files\StorageNotAvailableException;
  47. use OCP\Util;
  48. use Sabre\DAV\Client;
  49. use Sabre\DAV\Exception\NotFound;
  50. use Sabre\DAV\Xml\Property\ResourceType;
  51. use Sabre\HTTP\ClientException;
  52. use Sabre\HTTP\ClientHttpException;
  53. /**
  54. * Class DAV
  55. *
  56. * @package OC\Files\Storage
  57. */
  58. class DAV extends Common {
  59. /** @var string */
  60. protected $password;
  61. /** @var string */
  62. protected $user;
  63. /** @var string */
  64. protected $host;
  65. /** @var bool */
  66. protected $secure;
  67. /** @var string */
  68. protected $root;
  69. /** @var string */
  70. protected $certPath;
  71. /** @var bool */
  72. protected $ready;
  73. /** @var Client */
  74. private $client;
  75. /** @var ArrayCache */
  76. private $statCache;
  77. /** @var array */
  78. private static $tempFiles = [];
  79. /** @var \OCP\Http\Client\IClientService */
  80. private $httpClientService;
  81. /**
  82. * @param array $params
  83. * @throws \Exception
  84. */
  85. public function __construct($params) {
  86. $this->statCache = new ArrayCache();
  87. $this->httpClientService = \OC::$server->getHTTPClientService();
  88. if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
  89. $host = $params['host'];
  90. //remove leading http[s], will be generated in createBaseUri()
  91. if (substr($host, 0, 8) == "https://") $host = substr($host, 8);
  92. else if (substr($host, 0, 7) == "http://") $host = substr($host, 7);
  93. $this->host = $host;
  94. $this->user = $params['user'];
  95. $this->password = $params['password'];
  96. if (isset($params['secure'])) {
  97. if (is_string($params['secure'])) {
  98. $this->secure = ($params['secure'] === 'true');
  99. } else {
  100. $this->secure = (bool)$params['secure'];
  101. }
  102. } else {
  103. $this->secure = false;
  104. }
  105. if ($this->secure === true) {
  106. // inject mock for testing
  107. $certManager = \OC::$server->getCertificateManager();
  108. if (is_null($certManager)) { //no user
  109. $certManager = \OC::$server->getCertificateManager(null);
  110. }
  111. $certPath = $certManager->getAbsoluteBundlePath();
  112. if (file_exists($certPath)) {
  113. $this->certPath = $certPath;
  114. }
  115. }
  116. $this->root = isset($params['root']) ? $params['root'] : '/';
  117. if (!$this->root || $this->root[0] != '/') {
  118. $this->root = '/' . $this->root;
  119. }
  120. if (substr($this->root, -1, 1) != '/') {
  121. $this->root .= '/';
  122. }
  123. } else {
  124. throw new \Exception('Invalid webdav storage configuration');
  125. }
  126. }
  127. private function init() {
  128. if ($this->ready) {
  129. return;
  130. }
  131. $this->ready = true;
  132. $settings = array(
  133. 'baseUri' => $this->createBaseUri(),
  134. 'userName' => $this->user,
  135. 'password' => $this->password,
  136. );
  137. $proxy = \OC::$server->getConfig()->getSystemValue('proxy', '');
  138. if($proxy !== '') {
  139. $settings['proxy'] = $proxy;
  140. }
  141. $this->client = new Client($settings);
  142. $this->client->setThrowExceptions(true);
  143. if ($this->secure === true && $this->certPath) {
  144. $this->client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
  145. }
  146. }
  147. /**
  148. * Clear the stat cache
  149. */
  150. public function clearStatCache() {
  151. $this->statCache->clear();
  152. }
  153. /** {@inheritdoc} */
  154. public function getId() {
  155. return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
  156. }
  157. /** {@inheritdoc} */
  158. public function createBaseUri() {
  159. $baseUri = 'http';
  160. if ($this->secure) {
  161. $baseUri .= 's';
  162. }
  163. $baseUri .= '://' . $this->host . $this->root;
  164. return $baseUri;
  165. }
  166. /** {@inheritdoc} */
  167. public function mkdir($path) {
  168. $this->init();
  169. $path = $this->cleanPath($path);
  170. $result = $this->simpleResponse('MKCOL', $path, null, 201);
  171. if ($result) {
  172. $this->statCache->set($path, true);
  173. }
  174. return $result;
  175. }
  176. /** {@inheritdoc} */
  177. public function rmdir($path) {
  178. $this->init();
  179. $path = $this->cleanPath($path);
  180. // FIXME: some WebDAV impl return 403 when trying to DELETE
  181. // a non-empty folder
  182. $result = $this->simpleResponse('DELETE', $path . '/', null, 204);
  183. $this->statCache->clear($path . '/');
  184. $this->statCache->remove($path);
  185. return $result;
  186. }
  187. /** {@inheritdoc} */
  188. public function opendir($path) {
  189. $this->init();
  190. $path = $this->cleanPath($path);
  191. try {
  192. $response = $this->client->propfind(
  193. $this->encodePath($path),
  194. array(),
  195. 1
  196. );
  197. $id = md5('webdav' . $this->root . $path);
  198. $content = array();
  199. $files = array_keys($response);
  200. array_shift($files); //the first entry is the current directory
  201. if (!$this->statCache->hasKey($path)) {
  202. $this->statCache->set($path, true);
  203. }
  204. foreach ($files as $file) {
  205. $file = urldecode($file);
  206. // do not store the real entry, we might not have all properties
  207. if (!$this->statCache->hasKey($path)) {
  208. $this->statCache->set($file, true);
  209. }
  210. $file = basename($file);
  211. $content[] = $file;
  212. }
  213. return IteratorDirectory::wrap($content);
  214. } catch (ClientHttpException $e) {
  215. if ($e->getHttpStatus() === 404) {
  216. $this->statCache->clear($path . '/');
  217. $this->statCache->set($path, false);
  218. return false;
  219. }
  220. $this->convertException($e, $path);
  221. } catch (\Exception $e) {
  222. $this->convertException($e, $path);
  223. }
  224. return false;
  225. }
  226. /**
  227. * Propfind call with cache handling.
  228. *
  229. * First checks if information is cached.
  230. * If not, request it from the server then store to cache.
  231. *
  232. * @param string $path path to propfind
  233. *
  234. * @return array propfind response
  235. *
  236. * @throws NotFound
  237. */
  238. protected function propfind($path) {
  239. $path = $this->cleanPath($path);
  240. $cachedResponse = $this->statCache->get($path);
  241. if ($cachedResponse === false) {
  242. // we know it didn't exist
  243. throw new NotFound();
  244. }
  245. // we either don't know it, or we know it exists but need more details
  246. if (is_null($cachedResponse) || $cachedResponse === true) {
  247. $this->init();
  248. try {
  249. $response = $this->client->propfind(
  250. $this->encodePath($path),
  251. array(
  252. '{DAV:}getlastmodified',
  253. '{DAV:}getcontentlength',
  254. '{DAV:}getcontenttype',
  255. '{http://owncloud.org/ns}permissions',
  256. '{http://open-collaboration-services.org/ns}share-permissions',
  257. '{DAV:}resourcetype',
  258. '{DAV:}getetag',
  259. )
  260. );
  261. $this->statCache->set($path, $response);
  262. } catch (NotFound $e) {
  263. // remember that this path did not exist
  264. $this->statCache->clear($path . '/');
  265. $this->statCache->set($path, false);
  266. throw $e;
  267. }
  268. } else {
  269. $response = $cachedResponse;
  270. }
  271. return $response;
  272. }
  273. /** {@inheritdoc} */
  274. public function filetype($path) {
  275. try {
  276. $response = $this->propfind($path);
  277. $responseType = array();
  278. if (isset($response["{DAV:}resourcetype"])) {
  279. /** @var ResourceType[] $response */
  280. $responseType = $response["{DAV:}resourcetype"]->getValue();
  281. }
  282. return (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
  283. } catch (ClientHttpException $e) {
  284. if ($e->getHttpStatus() === 404) {
  285. return false;
  286. }
  287. $this->convertException($e, $path);
  288. } catch (\Exception $e) {
  289. $this->convertException($e, $path);
  290. }
  291. return false;
  292. }
  293. /** {@inheritdoc} */
  294. public function file_exists($path) {
  295. try {
  296. $path = $this->cleanPath($path);
  297. $cachedState = $this->statCache->get($path);
  298. if ($cachedState === false) {
  299. // we know the file doesn't exist
  300. return false;
  301. } else if (!is_null($cachedState)) {
  302. return true;
  303. }
  304. // need to get from server
  305. $this->propfind($path);
  306. return true; //no 404 exception
  307. } catch (ClientHttpException $e) {
  308. if ($e->getHttpStatus() === 404) {
  309. return false;
  310. }
  311. $this->convertException($e, $path);
  312. } catch (\Exception $e) {
  313. $this->convertException($e, $path);
  314. }
  315. return false;
  316. }
  317. /** {@inheritdoc} */
  318. public function unlink($path) {
  319. $this->init();
  320. $path = $this->cleanPath($path);
  321. $result = $this->simpleResponse('DELETE', $path, null, 204);
  322. $this->statCache->clear($path . '/');
  323. $this->statCache->remove($path);
  324. return $result;
  325. }
  326. /** {@inheritdoc} */
  327. public function fopen($path, $mode) {
  328. $this->init();
  329. $path = $this->cleanPath($path);
  330. switch ($mode) {
  331. case 'r':
  332. case 'rb':
  333. try {
  334. $response = $this->httpClientService
  335. ->newClient()
  336. ->get($this->createBaseUri() . $this->encodePath($path), [
  337. 'auth' => [$this->user, $this->password],
  338. 'stream' => true
  339. ]);
  340. } catch (RequestException $e) {
  341. if ($e->getResponse() instanceof ResponseInterface
  342. && $e->getResponse()->getStatusCode() === 404) {
  343. return false;
  344. } else {
  345. throw $e;
  346. }
  347. }
  348. if ($response->getStatusCode() !== Http::STATUS_OK) {
  349. if ($response->getStatusCode() === Http::STATUS_LOCKED) {
  350. throw new \OCP\Lock\LockedException($path);
  351. } else {
  352. Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), Util::ERROR);
  353. }
  354. }
  355. return $response->getBody();
  356. case 'w':
  357. case 'wb':
  358. case 'a':
  359. case 'ab':
  360. case 'r+':
  361. case 'w+':
  362. case 'wb+':
  363. case 'a+':
  364. case 'x':
  365. case 'x+':
  366. case 'c':
  367. case 'c+':
  368. //emulate these
  369. $tempManager = \OC::$server->getTempManager();
  370. if (strrpos($path, '.') !== false) {
  371. $ext = substr($path, strrpos($path, '.'));
  372. } else {
  373. $ext = '';
  374. }
  375. if ($this->file_exists($path)) {
  376. if (!$this->isUpdatable($path)) {
  377. return false;
  378. }
  379. if ($mode === 'w' or $mode === 'w+') {
  380. $tmpFile = $tempManager->getTemporaryFile($ext);
  381. } else {
  382. $tmpFile = $this->getCachedFile($path);
  383. }
  384. } else {
  385. if (!$this->isCreatable(dirname($path))) {
  386. return false;
  387. }
  388. $tmpFile = $tempManager->getTemporaryFile($ext);
  389. }
  390. Close::registerCallback($tmpFile, array($this, 'writeBack'));
  391. self::$tempFiles[$tmpFile] = $path;
  392. return fopen('close://' . $tmpFile, $mode);
  393. }
  394. }
  395. /**
  396. * @param string $tmpFile
  397. */
  398. public function writeBack($tmpFile) {
  399. if (isset(self::$tempFiles[$tmpFile])) {
  400. $this->uploadFile($tmpFile, self::$tempFiles[$tmpFile]);
  401. unlink($tmpFile);
  402. }
  403. }
  404. /** {@inheritdoc} */
  405. public function free_space($path) {
  406. $this->init();
  407. $path = $this->cleanPath($path);
  408. try {
  409. // TODO: cacheable ?
  410. $response = $this->client->propfind($this->encodePath($path), array('{DAV:}quota-available-bytes'));
  411. if (isset($response['{DAV:}quota-available-bytes'])) {
  412. return (int)$response['{DAV:}quota-available-bytes'];
  413. } else {
  414. return FileInfo::SPACE_UNKNOWN;
  415. }
  416. } catch (\Exception $e) {
  417. return FileInfo::SPACE_UNKNOWN;
  418. }
  419. }
  420. /** {@inheritdoc} */
  421. public function touch($path, $mtime = null) {
  422. $this->init();
  423. if (is_null($mtime)) {
  424. $mtime = time();
  425. }
  426. $path = $this->cleanPath($path);
  427. // if file exists, update the mtime, else create a new empty file
  428. if ($this->file_exists($path)) {
  429. try {
  430. $this->statCache->remove($path);
  431. $this->client->proppatch($this->encodePath($path), ['{DAV:}lastmodified' => $mtime]);
  432. // non-owncloud clients might not have accepted the property, need to recheck it
  433. $response = $this->client->propfind($this->encodePath($path), ['{DAV:}getlastmodified'], 0);
  434. if (isset($response['{DAV:}getlastmodified'])) {
  435. $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
  436. if ($remoteMtime !== $mtime) {
  437. // server has not accepted the mtime
  438. return false;
  439. }
  440. }
  441. } catch (ClientHttpException $e) {
  442. if ($e->getHttpStatus() === 501) {
  443. return false;
  444. }
  445. $this->convertException($e, $path);
  446. return false;
  447. } catch (\Exception $e) {
  448. $this->convertException($e, $path);
  449. return false;
  450. }
  451. } else {
  452. $this->file_put_contents($path, '');
  453. }
  454. return true;
  455. }
  456. /**
  457. * @param string $path
  458. * @param string $data
  459. * @return int
  460. */
  461. public function file_put_contents($path, $data) {
  462. $path = $this->cleanPath($path);
  463. $result = parent::file_put_contents($path, $data);
  464. $this->statCache->remove($path);
  465. return $result;
  466. }
  467. /**
  468. * @param string $path
  469. * @param string $target
  470. */
  471. protected function uploadFile($path, $target) {
  472. $this->init();
  473. // invalidate
  474. $target = $this->cleanPath($target);
  475. $this->statCache->remove($target);
  476. $source = fopen($path, 'r');
  477. $this->httpClientService
  478. ->newClient()
  479. ->put($this->createBaseUri() . $this->encodePath($target), [
  480. 'body' => $source,
  481. 'auth' => [$this->user, $this->password]
  482. ]);
  483. $this->removeCachedFile($target);
  484. }
  485. /** {@inheritdoc} */
  486. public function rename($path1, $path2) {
  487. $this->init();
  488. $path1 = $this->cleanPath($path1);
  489. $path2 = $this->cleanPath($path2);
  490. try {
  491. // overwrite directory ?
  492. if ($this->is_dir($path2)) {
  493. // needs trailing slash in destination
  494. $path2 = rtrim($path2, '/') . '/';
  495. }
  496. $this->client->request(
  497. 'MOVE',
  498. $this->encodePath($path1),
  499. null,
  500. [
  501. 'Destination' => $this->createBaseUri() . $this->encodePath($path2),
  502. ]
  503. );
  504. $this->statCache->clear($path1 . '/');
  505. $this->statCache->clear($path2 . '/');
  506. $this->statCache->set($path1, false);
  507. $this->statCache->set($path2, true);
  508. $this->removeCachedFile($path1);
  509. $this->removeCachedFile($path2);
  510. return true;
  511. } catch (\Exception $e) {
  512. $this->convertException($e);
  513. }
  514. return false;
  515. }
  516. /** {@inheritdoc} */
  517. public function copy($path1, $path2) {
  518. $this->init();
  519. $path1 = $this->cleanPath($path1);
  520. $path2 = $this->cleanPath($path2);
  521. try {
  522. // overwrite directory ?
  523. if ($this->is_dir($path2)) {
  524. // needs trailing slash in destination
  525. $path2 = rtrim($path2, '/') . '/';
  526. }
  527. $this->client->request(
  528. 'COPY',
  529. $this->encodePath($path1),
  530. null,
  531. [
  532. 'Destination' => $this->createBaseUri() . $this->encodePath($path2),
  533. ]
  534. );
  535. $this->statCache->clear($path2 . '/');
  536. $this->statCache->set($path2, true);
  537. $this->removeCachedFile($path2);
  538. return true;
  539. } catch (\Exception $e) {
  540. $this->convertException($e);
  541. }
  542. return false;
  543. }
  544. /** {@inheritdoc} */
  545. public function stat($path) {
  546. try {
  547. $response = $this->propfind($path);
  548. return array(
  549. 'mtime' => strtotime($response['{DAV:}getlastmodified']),
  550. 'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
  551. );
  552. } catch (ClientHttpException $e) {
  553. if ($e->getHttpStatus() === 404) {
  554. return array();
  555. }
  556. $this->convertException($e, $path);
  557. } catch (\Exception $e) {
  558. $this->convertException($e, $path);
  559. }
  560. return array();
  561. }
  562. /** {@inheritdoc} */
  563. public function getMimeType($path) {
  564. try {
  565. $response = $this->propfind($path);
  566. $responseType = array();
  567. if (isset($response["{DAV:}resourcetype"])) {
  568. /** @var ResourceType[] $response */
  569. $responseType = $response["{DAV:}resourcetype"]->getValue();
  570. }
  571. $type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
  572. if ($type == 'dir') {
  573. return 'httpd/unix-directory';
  574. } elseif (isset($response['{DAV:}getcontenttype'])) {
  575. return $response['{DAV:}getcontenttype'];
  576. } else {
  577. return false;
  578. }
  579. } catch (ClientHttpException $e) {
  580. if ($e->getHttpStatus() === 404) {
  581. return false;
  582. }
  583. $this->convertException($e, $path);
  584. } catch (\Exception $e) {
  585. $this->convertException($e, $path);
  586. }
  587. return false;
  588. }
  589. /**
  590. * @param string $path
  591. * @return string
  592. */
  593. public function cleanPath($path) {
  594. if ($path === '') {
  595. return $path;
  596. }
  597. $path = Filesystem::normalizePath($path);
  598. // remove leading slash
  599. return substr($path, 1);
  600. }
  601. /**
  602. * URL encodes the given path but keeps the slashes
  603. *
  604. * @param string $path to encode
  605. * @return string encoded path
  606. */
  607. private function encodePath($path) {
  608. // slashes need to stay
  609. return str_replace('%2F', '/', rawurlencode($path));
  610. }
  611. /**
  612. * @param string $method
  613. * @param string $path
  614. * @param string|resource|null $body
  615. * @param int $expected
  616. * @return bool
  617. * @throws StorageInvalidException
  618. * @throws StorageNotAvailableException
  619. */
  620. private function simpleResponse($method, $path, $body, $expected) {
  621. $path = $this->cleanPath($path);
  622. try {
  623. $response = $this->client->request($method, $this->encodePath($path), $body);
  624. return $response['statusCode'] == $expected;
  625. } catch (ClientHttpException $e) {
  626. if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
  627. $this->statCache->clear($path . '/');
  628. $this->statCache->set($path, false);
  629. return false;
  630. }
  631. $this->convertException($e, $path);
  632. } catch (\Exception $e) {
  633. $this->convertException($e, $path);
  634. }
  635. return false;
  636. }
  637. /**
  638. * check if curl is installed
  639. */
  640. public static function checkDependencies() {
  641. return true;
  642. }
  643. /** {@inheritdoc} */
  644. public function isUpdatable($path) {
  645. return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
  646. }
  647. /** {@inheritdoc} */
  648. public function isCreatable($path) {
  649. return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
  650. }
  651. /** {@inheritdoc} */
  652. public function isSharable($path) {
  653. return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
  654. }
  655. /** {@inheritdoc} */
  656. public function isDeletable($path) {
  657. return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
  658. }
  659. /** {@inheritdoc} */
  660. public function getPermissions($path) {
  661. $this->init();
  662. $path = $this->cleanPath($path);
  663. $response = $this->propfind($path);
  664. if (isset($response['{http://owncloud.org/ns}permissions'])) {
  665. return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
  666. } else if ($this->is_dir($path)) {
  667. return Constants::PERMISSION_ALL;
  668. } else if ($this->file_exists($path)) {
  669. return Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
  670. } else {
  671. return 0;
  672. }
  673. }
  674. /** {@inheritdoc} */
  675. public function getETag($path) {
  676. $this->init();
  677. $path = $this->cleanPath($path);
  678. $response = $this->propfind($path);
  679. if (isset($response['{DAV:}getetag'])) {
  680. return trim($response['{DAV:}getetag'], '"');
  681. }
  682. return parent::getEtag($path);
  683. }
  684. /**
  685. * @param string $permissionsString
  686. * @return int
  687. */
  688. protected function parsePermissions($permissionsString) {
  689. $permissions = Constants::PERMISSION_READ;
  690. if (strpos($permissionsString, 'R') !== false) {
  691. $permissions |= Constants::PERMISSION_SHARE;
  692. }
  693. if (strpos($permissionsString, 'D') !== false) {
  694. $permissions |= Constants::PERMISSION_DELETE;
  695. }
  696. if (strpos($permissionsString, 'W') !== false) {
  697. $permissions |= Constants::PERMISSION_UPDATE;
  698. }
  699. if (strpos($permissionsString, 'CK') !== false) {
  700. $permissions |= Constants::PERMISSION_CREATE;
  701. $permissions |= Constants::PERMISSION_UPDATE;
  702. }
  703. return $permissions;
  704. }
  705. /**
  706. * check if a file or folder has been updated since $time
  707. *
  708. * @param string $path
  709. * @param int $time
  710. * @throws \OCP\Files\StorageNotAvailableException
  711. * @return bool
  712. */
  713. public function hasUpdated($path, $time) {
  714. $this->init();
  715. $path = $this->cleanPath($path);
  716. try {
  717. // force refresh for $path
  718. $this->statCache->remove($path);
  719. $response = $this->propfind($path);
  720. if (isset($response['{DAV:}getetag'])) {
  721. $cachedData = $this->getCache()->get($path);
  722. $etag = null;
  723. if (isset($response['{DAV:}getetag'])) {
  724. $etag = trim($response['{DAV:}getetag'], '"');
  725. }
  726. if (!empty($etag) && $cachedData['etag'] !== $etag) {
  727. return true;
  728. } else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
  729. $sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
  730. return $sharePermissions !== $cachedData['permissions'];
  731. } else if (isset($response['{http://owncloud.org/ns}permissions'])) {
  732. $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
  733. return $permissions !== $cachedData['permissions'];
  734. } else {
  735. return false;
  736. }
  737. } else {
  738. $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
  739. return $remoteMtime > $time;
  740. }
  741. } catch (ClientHttpException $e) {
  742. if ($e->getHttpStatus() === 404 || $e->getHttpStatus() === 405) {
  743. if ($path === '') {
  744. // if root is gone it means the storage is not available
  745. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  746. }
  747. return false;
  748. }
  749. $this->convertException($e, $path);
  750. return false;
  751. } catch (\Exception $e) {
  752. $this->convertException($e, $path);
  753. return false;
  754. }
  755. }
  756. /**
  757. * Interpret the given exception and decide whether it is due to an
  758. * unavailable storage, invalid storage or other.
  759. * This will either throw StorageInvalidException, StorageNotAvailableException
  760. * or do nothing.
  761. *
  762. * @param Exception $e sabre exception
  763. * @param string $path optional path from the operation
  764. *
  765. * @throws StorageInvalidException if the storage is invalid, for example
  766. * when the authentication expired or is invalid
  767. * @throws StorageNotAvailableException if the storage is not available,
  768. * which might be temporary
  769. */
  770. private function convertException(Exception $e, $path = '') {
  771. \OC::$server->getLogger()->logException($e);
  772. Util::writeLog('files_external', $e->getMessage(), Util::ERROR);
  773. if ($e instanceof ClientHttpException) {
  774. if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
  775. throw new \OCP\Lock\LockedException($path);
  776. }
  777. if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
  778. // either password was changed or was invalid all along
  779. throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
  780. } else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
  781. // ignore exception for MethodNotAllowed, false will be returned
  782. return;
  783. }
  784. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  785. } else if ($e instanceof ClientException) {
  786. // connection timeout or refused, server could be temporarily down
  787. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  788. } else if ($e instanceof \InvalidArgumentException) {
  789. // parse error because the server returned HTML instead of XML,
  790. // possibly temporarily down
  791. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  792. } else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
  793. // rethrow
  794. throw $e;
  795. }
  796. // TODO: only log for now, but in the future need to wrap/rethrow exception
  797. }
  798. }