dav.php 22 KB

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