1
0

DAV.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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 Icewind\Streams\CallbackWrapper;
  38. use OC\Files\Filesystem;
  39. use OC\Files\Stream\Close;
  40. use Icewind\Streams\IteratorDirectory;
  41. use OC\MemCache\ArrayCache;
  42. use OCP\AppFramework\Http;
  43. use OCP\Constants;
  44. use OCP\Files;
  45. use OCP\Files\FileInfo;
  46. use OCP\Files\StorageInvalidException;
  47. use OCP\Files\StorageNotAvailableException;
  48. use OCP\Util;
  49. use Sabre\DAV\Client;
  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 $authType;
  65. /** @var string */
  66. protected $host;
  67. /** @var bool */
  68. protected $secure;
  69. /** @var string */
  70. protected $root;
  71. /** @var string */
  72. protected $certPath;
  73. /** @var bool */
  74. protected $ready;
  75. /** @var Client */
  76. protected $client;
  77. /** @var ArrayCache */
  78. protected $statCache;
  79. /** @var \OCP\Http\Client\IClientService */
  80. protected $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['authType'])) {
  97. $this->authType = $params['authType'];
  98. }
  99. if (isset($params['secure'])) {
  100. if (is_string($params['secure'])) {
  101. $this->secure = ($params['secure'] === 'true');
  102. } else {
  103. $this->secure = (bool)$params['secure'];
  104. }
  105. } else {
  106. $this->secure = false;
  107. }
  108. if ($this->secure === true) {
  109. // inject mock for testing
  110. $certManager = \OC::$server->getCertificateManager();
  111. if (is_null($certManager)) { //no user
  112. $certManager = \OC::$server->getCertificateManager(null);
  113. }
  114. $certPath = $certManager->getAbsoluteBundlePath();
  115. if (file_exists($certPath)) {
  116. $this->certPath = $certPath;
  117. }
  118. }
  119. $this->root = isset($params['root']) ? $params['root'] : '/';
  120. if (!$this->root || $this->root[0] != '/') {
  121. $this->root = '/' . $this->root;
  122. }
  123. if (substr($this->root, -1, 1) != '/') {
  124. $this->root .= '/';
  125. }
  126. } else {
  127. throw new \Exception('Invalid webdav storage configuration');
  128. }
  129. }
  130. protected function init() {
  131. if ($this->ready) {
  132. return;
  133. }
  134. $this->ready = true;
  135. $settings = [
  136. 'baseUri' => $this->createBaseUri(),
  137. 'userName' => $this->user,
  138. 'password' => $this->password,
  139. ];
  140. if (isset($this->authType)) {
  141. $settings['authType'] = $this->authType;
  142. }
  143. $proxy = \OC::$server->getConfig()->getSystemValue('proxy', '');
  144. if($proxy !== '') {
  145. $settings['proxy'] = $proxy;
  146. }
  147. $this->client = new Client($settings);
  148. $this->client->setThrowExceptions(true);
  149. if ($this->secure === true && $this->certPath) {
  150. $this->client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
  151. }
  152. }
  153. /**
  154. * Clear the stat cache
  155. */
  156. public function clearStatCache() {
  157. $this->statCache->clear();
  158. }
  159. /** {@inheritdoc} */
  160. public function getId() {
  161. return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
  162. }
  163. /** {@inheritdoc} */
  164. public function createBaseUri() {
  165. $baseUri = 'http';
  166. if ($this->secure) {
  167. $baseUri .= 's';
  168. }
  169. $baseUri .= '://' . $this->host . $this->root;
  170. return $baseUri;
  171. }
  172. /** {@inheritdoc} */
  173. public function mkdir($path) {
  174. $this->init();
  175. $path = $this->cleanPath($path);
  176. $result = $this->simpleResponse('MKCOL', $path, null, 201);
  177. if ($result) {
  178. $this->statCache->set($path, true);
  179. }
  180. return $result;
  181. }
  182. /** {@inheritdoc} */
  183. public function rmdir($path) {
  184. $this->init();
  185. $path = $this->cleanPath($path);
  186. // FIXME: some WebDAV impl return 403 when trying to DELETE
  187. // a non-empty folder
  188. $result = $this->simpleResponse('DELETE', $path . '/', null, 204);
  189. $this->statCache->clear($path . '/');
  190. $this->statCache->remove($path);
  191. return $result;
  192. }
  193. /** {@inheritdoc} */
  194. public function opendir($path) {
  195. $this->init();
  196. $path = $this->cleanPath($path);
  197. try {
  198. $response = $this->client->propFind(
  199. $this->encodePath($path),
  200. ['{DAV:}href'],
  201. 1
  202. );
  203. if ($response === false) {
  204. return false;
  205. }
  206. $content = [];
  207. $files = array_keys($response);
  208. array_shift($files); //the first entry is the current directory
  209. if (!$this->statCache->hasKey($path)) {
  210. $this->statCache->set($path, true);
  211. }
  212. foreach ($files as $file) {
  213. $file = urldecode($file);
  214. // do not store the real entry, we might not have all properties
  215. if (!$this->statCache->hasKey($path)) {
  216. $this->statCache->set($file, true);
  217. }
  218. $file = basename($file);
  219. $content[] = $file;
  220. }
  221. return IteratorDirectory::wrap($content);
  222. } catch (\Exception $e) {
  223. $this->convertException($e, $path);
  224. }
  225. return false;
  226. }
  227. /**
  228. * Propfind call with cache handling.
  229. *
  230. * First checks if information is cached.
  231. * If not, request it from the server then store to cache.
  232. *
  233. * @param string $path path to propfind
  234. *
  235. * @return array|boolean propfind response or false if the entry was not found
  236. *
  237. * @throws ClientHttpException
  238. */
  239. protected function propfind($path) {
  240. $path = $this->cleanPath($path);
  241. $cachedResponse = $this->statCache->get($path);
  242. // we either don't know it, or we know it exists but need more details
  243. if (is_null($cachedResponse) || $cachedResponse === true) {
  244. $this->init();
  245. try {
  246. $response = $this->client->propFind(
  247. $this->encodePath($path),
  248. array(
  249. '{DAV:}getlastmodified',
  250. '{DAV:}getcontentlength',
  251. '{DAV:}getcontenttype',
  252. '{http://owncloud.org/ns}permissions',
  253. '{http://open-collaboration-services.org/ns}share-permissions',
  254. '{DAV:}resourcetype',
  255. '{DAV:}getetag',
  256. )
  257. );
  258. $this->statCache->set($path, $response);
  259. } catch (ClientHttpException $e) {
  260. if ($e->getHttpStatus() === 404) {
  261. $this->statCache->clear($path . '/');
  262. $this->statCache->set($path, false);
  263. return false;
  264. }
  265. $this->convertException($e, $path);
  266. } catch (\Exception $e) {
  267. $this->convertException($e, $path);
  268. }
  269. } else {
  270. $response = $cachedResponse;
  271. }
  272. return $response;
  273. }
  274. /** {@inheritdoc} */
  275. public function filetype($path) {
  276. try {
  277. $response = $this->propfind($path);
  278. if ($response === false) {
  279. return false;
  280. }
  281. $responseType = [];
  282. if (isset($response["{DAV:}resourcetype"])) {
  283. /** @var ResourceType[] $response */
  284. $responseType = $response["{DAV:}resourcetype"]->getValue();
  285. }
  286. return (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
  287. } catch (\Exception $e) {
  288. $this->convertException($e, $path);
  289. }
  290. return false;
  291. }
  292. /** {@inheritdoc} */
  293. public function file_exists($path) {
  294. try {
  295. $path = $this->cleanPath($path);
  296. $cachedState = $this->statCache->get($path);
  297. if ($cachedState === false) {
  298. // we know the file doesn't exist
  299. return false;
  300. } else if (!is_null($cachedState)) {
  301. return true;
  302. }
  303. // need to get from server
  304. return ($this->propfind($path) !== false);
  305. } catch (\Exception $e) {
  306. $this->convertException($e, $path);
  307. }
  308. return false;
  309. }
  310. /** {@inheritdoc} */
  311. public function unlink($path) {
  312. $this->init();
  313. $path = $this->cleanPath($path);
  314. $result = $this->simpleResponse('DELETE', $path, null, 204);
  315. $this->statCache->clear($path . '/');
  316. $this->statCache->remove($path);
  317. return $result;
  318. }
  319. /** {@inheritdoc} */
  320. public function fopen($path, $mode) {
  321. $this->init();
  322. $path = $this->cleanPath($path);
  323. switch ($mode) {
  324. case 'r':
  325. case 'rb':
  326. try {
  327. $response = $this->httpClientService
  328. ->newClient()
  329. ->get($this->createBaseUri() . $this->encodePath($path), [
  330. 'auth' => [$this->user, $this->password],
  331. 'stream' => true
  332. ]);
  333. } catch (RequestException $e) {
  334. if ($e->getResponse() instanceof ResponseInterface
  335. && $e->getResponse()->getStatusCode() === 404) {
  336. return false;
  337. } else {
  338. throw $e;
  339. }
  340. }
  341. if ($response->getStatusCode() !== Http::STATUS_OK) {
  342. if ($response->getStatusCode() === Http::STATUS_LOCKED) {
  343. throw new \OCP\Lock\LockedException($path);
  344. } else {
  345. Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), Util::ERROR);
  346. }
  347. }
  348. return $response->getBody();
  349. case 'w':
  350. case 'wb':
  351. case 'a':
  352. case 'ab':
  353. case 'r+':
  354. case 'w+':
  355. case 'wb+':
  356. case 'a+':
  357. case 'x':
  358. case 'x+':
  359. case 'c':
  360. case 'c+':
  361. //emulate these
  362. $tempManager = \OC::$server->getTempManager();
  363. if (strrpos($path, '.') !== false) {
  364. $ext = substr($path, strrpos($path, '.'));
  365. } else {
  366. $ext = '';
  367. }
  368. if ($this->file_exists($path)) {
  369. if (!$this->isUpdatable($path)) {
  370. return false;
  371. }
  372. if ($mode === 'w' or $mode === 'w+') {
  373. $tmpFile = $tempManager->getTemporaryFile($ext);
  374. } else {
  375. $tmpFile = $this->getCachedFile($path);
  376. }
  377. } else {
  378. if (!$this->isCreatable(dirname($path))) {
  379. return false;
  380. }
  381. $tmpFile = $tempManager->getTemporaryFile($ext);
  382. }
  383. $handle = fopen($tmpFile, $mode);
  384. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  385. $this->writeBack($tmpFile, $path);
  386. });
  387. }
  388. }
  389. /**
  390. * @param string $tmpFile
  391. */
  392. public function writeBack($tmpFile, $path) {
  393. $this->uploadFile($tmpFile, $path);
  394. unlink($tmpFile);
  395. }
  396. /** {@inheritdoc} */
  397. public function free_space($path) {
  398. $this->init();
  399. $path = $this->cleanPath($path);
  400. try {
  401. // TODO: cacheable ?
  402. $response = $this->client->propfind($this->encodePath($path), ['{DAV:}quota-available-bytes']);
  403. if ($response === false) {
  404. return FileInfo::SPACE_UNKNOWN;
  405. }
  406. if (isset($response['{DAV:}quota-available-bytes'])) {
  407. return (int)$response['{DAV:}quota-available-bytes'];
  408. } else {
  409. return FileInfo::SPACE_UNKNOWN;
  410. }
  411. } catch (\Exception $e) {
  412. return FileInfo::SPACE_UNKNOWN;
  413. }
  414. }
  415. /** {@inheritdoc} */
  416. public function touch($path, $mtime = null) {
  417. $this->init();
  418. if (is_null($mtime)) {
  419. $mtime = time();
  420. }
  421. $path = $this->cleanPath($path);
  422. // if file exists, update the mtime, else create a new empty file
  423. if ($this->file_exists($path)) {
  424. try {
  425. $this->statCache->remove($path);
  426. $this->client->proppatch($this->encodePath($path), ['{DAV:}lastmodified' => $mtime]);
  427. // non-owncloud clients might not have accepted the property, need to recheck it
  428. $response = $this->client->propfind($this->encodePath($path), ['{DAV:}getlastmodified'], 0);
  429. if ($response === false) {
  430. return false;
  431. }
  432. if (isset($response['{DAV:}getlastmodified'])) {
  433. $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
  434. if ($remoteMtime !== $mtime) {
  435. // server has not accepted the mtime
  436. return false;
  437. }
  438. }
  439. } catch (ClientHttpException $e) {
  440. if ($e->getHttpStatus() === 501) {
  441. return false;
  442. }
  443. $this->convertException($e, $path);
  444. return false;
  445. } catch (\Exception $e) {
  446. $this->convertException($e, $path);
  447. return false;
  448. }
  449. } else {
  450. $this->file_put_contents($path, '');
  451. }
  452. return true;
  453. }
  454. /**
  455. * @param string $path
  456. * @param string $data
  457. * @return int
  458. */
  459. public function file_put_contents($path, $data) {
  460. $path = $this->cleanPath($path);
  461. $result = parent::file_put_contents($path, $data);
  462. $this->statCache->remove($path);
  463. return $result;
  464. }
  465. /**
  466. * @param string $path
  467. * @param string $target
  468. */
  469. protected function uploadFile($path, $target) {
  470. $this->init();
  471. // invalidate
  472. $target = $this->cleanPath($target);
  473. $this->statCache->remove($target);
  474. $source = fopen($path, 'r');
  475. $this->httpClientService
  476. ->newClient()
  477. ->put($this->createBaseUri() . $this->encodePath($target), [
  478. 'body' => $source,
  479. 'auth' => [$this->user, $this->password]
  480. ]);
  481. $this->removeCachedFile($target);
  482. }
  483. /** {@inheritdoc} */
  484. public function rename($path1, $path2) {
  485. $this->init();
  486. $path1 = $this->cleanPath($path1);
  487. $path2 = $this->cleanPath($path2);
  488. try {
  489. // overwrite directory ?
  490. if ($this->is_dir($path2)) {
  491. // needs trailing slash in destination
  492. $path2 = rtrim($path2, '/') . '/';
  493. }
  494. $this->client->request(
  495. 'MOVE',
  496. $this->encodePath($path1),
  497. null,
  498. [
  499. 'Destination' => $this->createBaseUri() . $this->encodePath($path2),
  500. ]
  501. );
  502. $this->statCache->clear($path1 . '/');
  503. $this->statCache->clear($path2 . '/');
  504. $this->statCache->set($path1, false);
  505. $this->statCache->set($path2, true);
  506. $this->removeCachedFile($path1);
  507. $this->removeCachedFile($path2);
  508. return true;
  509. } catch (\Exception $e) {
  510. $this->convertException($e);
  511. }
  512. return false;
  513. }
  514. /** {@inheritdoc} */
  515. public function copy($path1, $path2) {
  516. $this->init();
  517. $path1 = $this->cleanPath($path1);
  518. $path2 = $this->cleanPath($path2);
  519. try {
  520. // overwrite directory ?
  521. if ($this->is_dir($path2)) {
  522. // needs trailing slash in destination
  523. $path2 = rtrim($path2, '/') . '/';
  524. }
  525. $this->client->request(
  526. 'COPY',
  527. $this->encodePath($path1),
  528. null,
  529. [
  530. 'Destination' => $this->createBaseUri() . $this->encodePath($path2),
  531. ]
  532. );
  533. $this->statCache->clear($path2 . '/');
  534. $this->statCache->set($path2, true);
  535. $this->removeCachedFile($path2);
  536. return true;
  537. } catch (\Exception $e) {
  538. $this->convertException($e);
  539. }
  540. return false;
  541. }
  542. /** {@inheritdoc} */
  543. public function stat($path) {
  544. try {
  545. $response = $this->propfind($path);
  546. if (!$response) {
  547. return false;
  548. }
  549. return [
  550. 'mtime' => strtotime($response['{DAV:}getlastmodified']),
  551. 'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
  552. ];
  553. } catch (\Exception $e) {
  554. $this->convertException($e, $path);
  555. }
  556. return array();
  557. }
  558. /** {@inheritdoc} */
  559. public function getMimeType($path) {
  560. try {
  561. $response = $this->propfind($path);
  562. if ($response === false) {
  563. return false;
  564. }
  565. $responseType = [];
  566. if (isset($response["{DAV:}resourcetype"])) {
  567. /** @var ResourceType[] $response */
  568. $responseType = $response["{DAV:}resourcetype"]->getValue();
  569. }
  570. $type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
  571. if ($type == 'dir') {
  572. return 'httpd/unix-directory';
  573. } elseif (isset($response['{DAV:}getcontenttype'])) {
  574. return $response['{DAV:}getcontenttype'];
  575. } else {
  576. return false;
  577. }
  578. } catch (\Exception $e) {
  579. $this->convertException($e, $path);
  580. }
  581. return false;
  582. }
  583. /**
  584. * @param string $path
  585. * @return string
  586. */
  587. public function cleanPath($path) {
  588. if ($path === '') {
  589. return $path;
  590. }
  591. $path = Filesystem::normalizePath($path);
  592. // remove leading slash
  593. return substr($path, 1);
  594. }
  595. /**
  596. * URL encodes the given path but keeps the slashes
  597. *
  598. * @param string $path to encode
  599. * @return string encoded path
  600. */
  601. protected function encodePath($path) {
  602. // slashes need to stay
  603. return str_replace('%2F', '/', rawurlencode($path));
  604. }
  605. /**
  606. * @param string $method
  607. * @param string $path
  608. * @param string|resource|null $body
  609. * @param int $expected
  610. * @return bool
  611. * @throws StorageInvalidException
  612. * @throws StorageNotAvailableException
  613. */
  614. protected function simpleResponse($method, $path, $body, $expected) {
  615. $path = $this->cleanPath($path);
  616. try {
  617. $response = $this->client->request($method, $this->encodePath($path), $body);
  618. return $response['statusCode'] == $expected;
  619. } catch (ClientHttpException $e) {
  620. if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
  621. $this->statCache->clear($path . '/');
  622. $this->statCache->set($path, false);
  623. return false;
  624. }
  625. $this->convertException($e, $path);
  626. } catch (\Exception $e) {
  627. $this->convertException($e, $path);
  628. }
  629. return false;
  630. }
  631. /**
  632. * check if curl is installed
  633. */
  634. public static function checkDependencies() {
  635. return true;
  636. }
  637. /** {@inheritdoc} */
  638. public function isUpdatable($path) {
  639. return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
  640. }
  641. /** {@inheritdoc} */
  642. public function isCreatable($path) {
  643. return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
  644. }
  645. /** {@inheritdoc} */
  646. public function isSharable($path) {
  647. return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
  648. }
  649. /** {@inheritdoc} */
  650. public function isDeletable($path) {
  651. return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
  652. }
  653. /** {@inheritdoc} */
  654. public function getPermissions($path) {
  655. $this->init();
  656. $path = $this->cleanPath($path);
  657. $response = $this->propfind($path);
  658. if ($response === false) {
  659. return 0;
  660. }
  661. if (isset($response['{http://owncloud.org/ns}permissions'])) {
  662. return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
  663. } else if ($this->is_dir($path)) {
  664. return Constants::PERMISSION_ALL;
  665. } else if ($this->file_exists($path)) {
  666. return Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
  667. } else {
  668. return 0;
  669. }
  670. }
  671. /** {@inheritdoc} */
  672. public function getETag($path) {
  673. $this->init();
  674. $path = $this->cleanPath($path);
  675. $response = $this->propfind($path);
  676. if ($response === false) {
  677. return null;
  678. }
  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 ($response === false) {
  721. if ($path === '') {
  722. // if root is gone it means the storage is not available
  723. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  724. }
  725. return false;
  726. }
  727. if (isset($response['{DAV:}getetag'])) {
  728. $cachedData = $this->getCache()->get($path);
  729. $etag = null;
  730. if (isset($response['{DAV:}getetag'])) {
  731. $etag = trim($response['{DAV:}getetag'], '"');
  732. }
  733. if (!empty($etag) && $cachedData['etag'] !== $etag) {
  734. return true;
  735. } else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
  736. $sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
  737. return $sharePermissions !== $cachedData['permissions'];
  738. } else if (isset($response['{http://owncloud.org/ns}permissions'])) {
  739. $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
  740. return $permissions !== $cachedData['permissions'];
  741. } else {
  742. return false;
  743. }
  744. } else {
  745. $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
  746. return $remoteMtime > $time;
  747. }
  748. } catch (ClientHttpException $e) {
  749. if ($e->getHttpStatus() === 405) {
  750. if ($path === '') {
  751. // if root is gone it means the storage is not available
  752. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  753. }
  754. return false;
  755. }
  756. $this->convertException($e, $path);
  757. return false;
  758. } catch (\Exception $e) {
  759. $this->convertException($e, $path);
  760. return false;
  761. }
  762. }
  763. /**
  764. * Interpret the given exception and decide whether it is due to an
  765. * unavailable storage, invalid storage or other.
  766. * This will either throw StorageInvalidException, StorageNotAvailableException
  767. * or do nothing.
  768. *
  769. * @param Exception $e sabre exception
  770. * @param string $path optional path from the operation
  771. *
  772. * @throws StorageInvalidException if the storage is invalid, for example
  773. * when the authentication expired or is invalid
  774. * @throws StorageNotAvailableException if the storage is not available,
  775. * which might be temporary
  776. */
  777. protected function convertException(Exception $e, $path = '') {
  778. \OC::$server->getLogger()->logException($e);
  779. Util::writeLog('files_external', $e->getMessage(), Util::ERROR);
  780. if ($e instanceof ClientHttpException) {
  781. if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
  782. throw new \OCP\Lock\LockedException($path);
  783. }
  784. if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
  785. // either password was changed or was invalid all along
  786. throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
  787. } else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
  788. // ignore exception for MethodNotAllowed, false will be returned
  789. return;
  790. }
  791. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  792. } else if ($e instanceof ClientException) {
  793. // connection timeout or refused, server could be temporarily down
  794. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  795. } else if ($e instanceof \InvalidArgumentException) {
  796. // parse error because the server returned HTML instead of XML,
  797. // possibly temporarily down
  798. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  799. } else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
  800. // rethrow
  801. throw $e;
  802. }
  803. // TODO: only log for now, but in the future need to wrap/rethrow exception
  804. }
  805. }