WebDav.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. use GuzzleHttp\Client as GClient;
  8. use PHPUnit\Framework\Assert;
  9. use Psr\Http\Message\ResponseInterface;
  10. use Sabre\DAV\Client as SClient;
  11. use Sabre\DAV\Xml\Property\ResourceType;
  12. require __DIR__ . '/../../vendor/autoload.php';
  13. trait WebDav {
  14. use Sharing;
  15. private string $davPath = 'remote.php/webdav';
  16. private bool $usingOldDavPath = true;
  17. private ?array $storedETAG = null; // map with user as key and another map as value, which has path as key and etag as value
  18. private ?int $storedFileID = null;
  19. /** @var ResponseInterface */
  20. private $response;
  21. private array $parsedResponse = [];
  22. private string $s3MultipartDestination;
  23. private string $uploadId;
  24. /** @var string[] */
  25. private array $parts = [];
  26. /**
  27. * @Given /^using dav path "([^"]*)"$/
  28. */
  29. public function usingDavPath($davPath) {
  30. $this->davPath = $davPath;
  31. }
  32. /**
  33. * @Given /^using old dav path$/
  34. */
  35. public function usingOldDavPath() {
  36. $this->davPath = 'remote.php/webdav';
  37. $this->usingOldDavPath = true;
  38. }
  39. /**
  40. * @Given /^using new dav path$/
  41. */
  42. public function usingNewDavPath() {
  43. $this->davPath = 'remote.php/dav';
  44. $this->usingOldDavPath = false;
  45. }
  46. /**
  47. * @Given /^using new public dav path$/
  48. */
  49. public function usingNewPublicDavPath() {
  50. $this->davPath = 'public.php/dav';
  51. $this->usingOldDavPath = false;
  52. }
  53. public function getDavFilesPath($user) {
  54. if ($this->usingOldDavPath === true) {
  55. return $this->davPath;
  56. } else {
  57. return $this->davPath . '/files/' . $user;
  58. }
  59. }
  60. public function makeDavRequest($user, $method, $path, $headers, $body = null, $type = 'files') {
  61. if ($type === 'files') {
  62. $fullUrl = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . "$path";
  63. } elseif ($type === 'uploads') {
  64. $fullUrl = substr($this->baseUrl, 0, -4) . $this->davPath . "$path";
  65. } else {
  66. $fullUrl = substr($this->baseUrl, 0, -4) . $this->davPath . '/' . $type . "$path";
  67. }
  68. $client = new GClient();
  69. $options = [
  70. 'headers' => $headers,
  71. 'body' => $body
  72. ];
  73. if ($user === 'admin') {
  74. $options['auth'] = $this->adminUser;
  75. } elseif ($user !== '') {
  76. $options['auth'] = [$user, $this->regularUser];
  77. }
  78. return $client->request($method, $fullUrl, $options);
  79. }
  80. /**
  81. * @Given /^User "([^"]*)" moved (file|folder|entry) "([^"]*)" to "([^"]*)"$/
  82. * @param string $user
  83. * @param string $fileSource
  84. * @param string $fileDestination
  85. */
  86. public function userMovedFile($user, $entry, $fileSource, $fileDestination) {
  87. $fullUrl = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user);
  88. $headers['Destination'] = $fullUrl . $fileDestination;
  89. $this->response = $this->makeDavRequest($user, 'MOVE', $fileSource, $headers);
  90. Assert::assertEquals(201, $this->response->getStatusCode());
  91. }
  92. /**
  93. * @When /^User "([^"]*)" moves (file|folder|entry) "([^"]*)" to "([^"]*)"$/
  94. * @param string $user
  95. * @param string $fileSource
  96. * @param string $fileDestination
  97. */
  98. public function userMovesFile($user, $entry, $fileSource, $fileDestination) {
  99. $fullUrl = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user);
  100. $headers['Destination'] = $fullUrl . $fileDestination;
  101. try {
  102. $this->response = $this->makeDavRequest($user, 'MOVE', $fileSource, $headers);
  103. } catch (\GuzzleHttp\Exception\ClientException $e) {
  104. $this->response = $e->getResponse();
  105. }
  106. }
  107. /**
  108. * @When /^User "([^"]*)" copies file "([^"]*)" to "([^"]*)"$/
  109. * @param string $user
  110. * @param string $fileSource
  111. * @param string $fileDestination
  112. */
  113. public function userCopiesFileTo($user, $fileSource, $fileDestination) {
  114. $fullUrl = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user);
  115. $headers['Destination'] = $fullUrl . $fileDestination;
  116. try {
  117. $this->response = $this->makeDavRequest($user, 'COPY', $fileSource, $headers);
  118. } catch (\GuzzleHttp\Exception\ClientException $e) {
  119. // 4xx and 5xx responses cause an exception
  120. $this->response = $e->getResponse();
  121. }
  122. }
  123. /**
  124. * @When /^Downloading file "([^"]*)" with range "([^"]*)"$/
  125. * @param string $fileSource
  126. * @param string $range
  127. */
  128. public function downloadFileWithRange($fileSource, $range) {
  129. $headers['Range'] = $range;
  130. $this->response = $this->makeDavRequest($this->currentUser, 'GET', $fileSource, $headers);
  131. }
  132. /**
  133. * @When /^Downloading last public shared file with range "([^"]*)"$/
  134. * @param string $range
  135. */
  136. public function downloadPublicFileWithRange($range) {
  137. $token = $this->lastShareData->data->token;
  138. $fullUrl = substr($this->baseUrl, 0, -4) . "public.php/dav/files/$token";
  139. $client = new GClient();
  140. $options = [];
  141. $options['headers'] = [
  142. 'Range' => $range
  143. ];
  144. $this->response = $client->request('GET', $fullUrl, $options);
  145. }
  146. /**
  147. * @When /^Downloading last public shared file inside a folder "([^"]*)" with range "([^"]*)"$/
  148. * @param string $range
  149. */
  150. public function downloadPublicFileInsideAFolderWithRange($path, $range) {
  151. $token = $this->lastShareData->data->token;
  152. $fullUrl = substr($this->baseUrl, 0, -4) . "public.php/dav/files/$token/$path";
  153. $client = new GClient();
  154. $options = [
  155. 'headers' => [
  156. 'Range' => $range
  157. ]
  158. ];
  159. $this->response = $client->request('GET', $fullUrl, $options);
  160. }
  161. /**
  162. * @Then /^Downloaded content should be "([^"]*)"$/
  163. * @param string $content
  164. */
  165. public function downloadedContentShouldBe($content) {
  166. Assert::assertEquals($content, (string)$this->response->getBody());
  167. }
  168. /**
  169. * @Then /^File "([^"]*)" should have prop "([^"]*):([^"]*)" equal to "([^"]*)"$/
  170. * @param string $file
  171. * @param string $prefix
  172. * @param string $prop
  173. * @param string $value
  174. */
  175. public function checkPropForFile($file, $prefix, $prop, $value) {
  176. $elementList = $this->propfindFile($this->currentUser, $file, "<$prefix:$prop/>");
  177. $property = $elementList['/' . $this->getDavFilesPath($this->currentUser) . $file][200]["{DAV:}$prop"];
  178. Assert::assertEquals($property, $value);
  179. }
  180. /**
  181. * @Then /^Image search should work$/
  182. */
  183. public function search(): void {
  184. $this->searchFile($this->currentUser);
  185. Assert::assertEquals(207, $this->response->getStatusCode());
  186. }
  187. /**
  188. * @Then /^Favorite search should work$/
  189. */
  190. public function searchFavorite(): void {
  191. $this->searchFile(
  192. $this->currentUser,
  193. '<oc:favorite/>',
  194. null,
  195. '<d:eq>
  196. <d:prop>
  197. <oc:favorite/>
  198. </d:prop>
  199. <d:literal>yes</d:literal>
  200. </d:eq>'
  201. );
  202. Assert::assertEquals(207, $this->response->getStatusCode());
  203. }
  204. /**
  205. * @Then /^Downloaded content when downloading file "([^"]*)" with range "([^"]*)" should be "([^"]*)"$/
  206. * @param string $fileSource
  207. * @param string $range
  208. * @param string $content
  209. */
  210. public function downloadedContentWhenDownloadindShouldBe($fileSource, $range, $content) {
  211. $this->downloadFileWithRange($fileSource, $range);
  212. $this->downloadedContentShouldBe($content);
  213. }
  214. /**
  215. * @When Downloading folder :folderName
  216. */
  217. public function downloadingFolder(string $folderName) {
  218. try {
  219. $this->response = $this->makeDavRequest($this->currentUser, 'GET', $folderName, ['Accept' => 'application/zip']);
  220. } catch (\GuzzleHttp\Exception\ClientException $e) {
  221. $this->response = $e->getResponse();
  222. }
  223. }
  224. /**
  225. * @When Downloading public folder :folderName
  226. */
  227. public function downloadPublicFolder(string $folderName) {
  228. $token = $this->lastShareData->data->token;
  229. $fullUrl = substr($this->baseUrl, 0, -4) . "public.php/dav/files/$token/$folderName";
  230. $client = new GClient();
  231. $options = [];
  232. $options['headers'] = [
  233. 'Accept' => 'application/zip'
  234. ];
  235. $this->response = $client->request('GET', $fullUrl, $options);
  236. }
  237. /**
  238. * @When Downloading file :fileName
  239. * @param string $fileName
  240. */
  241. public function downloadingFile($fileName) {
  242. try {
  243. $this->response = $this->makeDavRequest($this->currentUser, 'GET', $fileName, []);
  244. } catch (\GuzzleHttp\Exception\ClientException $e) {
  245. $this->response = $e->getResponse();
  246. }
  247. }
  248. /**
  249. * @When Downloading public file :filename
  250. */
  251. public function downloadingPublicFile(string $filename) {
  252. $token = $this->lastShareData->data->token;
  253. $fullUrl = substr($this->baseUrl, 0, -4) . "public.php/dav/files/$token/$filename";
  254. $client = new GClient();
  255. $options = [
  256. 'headers' => [
  257. 'X-Requested-With' => 'XMLHttpRequest',
  258. ]
  259. ];
  260. try {
  261. $this->response = $client->request('GET', $fullUrl, $options);
  262. } catch (\GuzzleHttp\Exception\ClientException $e) {
  263. $this->response = $e->getResponse();
  264. }
  265. }
  266. /**
  267. * @When Downloading public file :filename without ajax header
  268. */
  269. public function downloadingPublicFileWithoutHeader(string $filename) {
  270. $token = $this->lastShareData->data->token;
  271. $fullUrl = substr($this->baseUrl, 0, -4) . "public.php/dav/files/$token/$filename";
  272. $client = new GClient();
  273. try {
  274. $this->response = $client->request('GET', $fullUrl);
  275. } catch (\GuzzleHttp\Exception\ClientException $e) {
  276. $this->response = $e->getResponse();
  277. }
  278. }
  279. /**
  280. * @Then Downloaded content should start with :start
  281. * @param int $start
  282. * @throws \Exception
  283. */
  284. public function downloadedContentShouldStartWith($start) {
  285. if (strpos($this->response->getBody()->getContents(), $start) !== 0) {
  286. throw new \Exception(
  287. sprintf(
  288. "Expected '%s', got '%s'",
  289. $start,
  290. $this->response->getBody()->getContents()
  291. )
  292. );
  293. }
  294. }
  295. /**
  296. * @Then /^as "([^"]*)" gets properties of (file|folder|entry) "([^"]*)" with$/
  297. * @param string $user
  298. * @param string $elementType
  299. * @param string $path
  300. * @param \Behat\Gherkin\Node\TableNode|null $propertiesTable
  301. */
  302. public function asGetsPropertiesOfFolderWith($user, $elementType, $path, $propertiesTable) {
  303. $properties = null;
  304. if ($propertiesTable instanceof \Behat\Gherkin\Node\TableNode) {
  305. foreach ($propertiesTable->getRows() as $row) {
  306. $properties[] = $row[0];
  307. }
  308. }
  309. $this->response = $this->listFolder($user, $path, 0, $properties);
  310. }
  311. /**
  312. * @Then /^as "([^"]*)" the (file|folder|entry) "([^"]*)" does not exist$/
  313. * @param string $user
  314. * @param string $entry
  315. * @param string $path
  316. * @param \Behat\Gherkin\Node\TableNode|null $propertiesTable
  317. */
  318. public function asTheFileOrFolderDoesNotExist($user, $entry, $path) {
  319. $client = $this->getSabreClient($user);
  320. $response = $client->request('HEAD', $this->makeSabrePath($user, $path));
  321. if ($response['statusCode'] !== 404) {
  322. throw new \Exception($entry . ' "' . $path . '" expected to not exist (status code ' . $response['statusCode'] . ', expected 404)');
  323. }
  324. return $response;
  325. }
  326. /**
  327. * @Then /^as "([^"]*)" the (file|folder|entry) "([^"]*)" exists$/
  328. * @param string $user
  329. * @param string $entry
  330. * @param string $path
  331. */
  332. public function asTheFileOrFolderExists($user, $entry, $path) {
  333. $this->response = $this->listFolder($user, $path, 0);
  334. }
  335. /**
  336. * @Then the response should be empty
  337. * @throws \Exception
  338. */
  339. public function theResponseShouldBeEmpty(): void {
  340. $response = ($this->response instanceof ResponseInterface) ? $this->convertResponseToDavEntries() : $this->response;
  341. if ($response === []) {
  342. return;
  343. }
  344. throw new \Exception('response is not empty');
  345. }
  346. /**
  347. * @Then the single response should contain a property :key with value :value
  348. * @param string $key
  349. * @param string $expectedValue
  350. * @throws \Exception
  351. */
  352. public function theSingleResponseShouldContainAPropertyWithValue($key, $expectedValue) {
  353. $response = ($this->response instanceof ResponseInterface) ? $this->convertResponseToDavSingleEntry() : $this->response;
  354. if (!array_key_exists($key, $response)) {
  355. throw new \Exception("Cannot find property \"$key\" with \"$expectedValue\"");
  356. }
  357. $value = $response[$key];
  358. if ($value instanceof ResourceType) {
  359. $value = $value->getValue();
  360. if (empty($value)) {
  361. $value = '';
  362. } else {
  363. $value = $value[0];
  364. }
  365. }
  366. if ($value != $expectedValue) {
  367. throw new \Exception("Property \"$key\" found with value \"$value\", expected \"$expectedValue\"");
  368. }
  369. }
  370. /**
  371. * @Then the response should contain a share-types property with
  372. */
  373. public function theResponseShouldContainAShareTypesPropertyWith($table) {
  374. $keys = $this->response;
  375. if (!array_key_exists('{http://owncloud.org/ns}share-types', $keys)) {
  376. throw new \Exception('Cannot find property "{http://owncloud.org/ns}share-types"');
  377. }
  378. $foundTypes = [];
  379. $data = $keys['{http://owncloud.org/ns}share-types'];
  380. foreach ($data as $item) {
  381. if ($item['name'] !== '{http://owncloud.org/ns}share-type') {
  382. throw new \Exception('Invalid property found: "' . $item['name'] . '"');
  383. }
  384. $foundTypes[] = $item['value'];
  385. }
  386. foreach ($table->getRows() as $row) {
  387. $key = array_search($row[0], $foundTypes);
  388. if ($key === false) {
  389. throw new \Exception('Expected type ' . $row[0] . ' not found');
  390. }
  391. unset($foundTypes[$key]);
  392. }
  393. if ($foundTypes !== []) {
  394. throw new \Exception('Found more share types then specified: ' . $foundTypes);
  395. }
  396. }
  397. /**
  398. * @Then the response should contain an empty property :property
  399. * @param string $property
  400. * @throws \Exception
  401. */
  402. public function theResponseShouldContainAnEmptyProperty($property) {
  403. $properties = $this->response;
  404. if (!array_key_exists($property, $properties)) {
  405. throw new \Exception("Cannot find property \"$property\"");
  406. }
  407. if ($properties[$property] !== null) {
  408. throw new \Exception("Property \"$property\" is not empty");
  409. }
  410. }
  411. /*Returns the elements of a propfind, $folderDepth requires 1 to see elements without children*/
  412. public function listFolder($user, $path, $folderDepth, $properties = null) {
  413. $client = $this->getSabreClient($user);
  414. if (!$properties) {
  415. $properties = [
  416. '{DAV:}getetag'
  417. ];
  418. }
  419. $response = $client->propfind($this->makeSabrePath($user, $path), $properties, $folderDepth);
  420. return $response;
  421. }
  422. /**
  423. * Returns the elements of a profind command
  424. * @param string $properties properties which needs to be included in the report
  425. * @param string $filterRules filter-rules to choose what needs to appear in the report
  426. */
  427. public function propfindFile(string $user, string $path, string $properties = '') {
  428. $client = $this->getSabreClient($user);
  429. $body = '<?xml version="1.0" encoding="utf-8" ?>
  430. <d:propfind xmlns:d="DAV:"
  431. xmlns:oc="http://owncloud.org/ns"
  432. xmlns:nc="http://nextcloud.org/ns"
  433. xmlns:ocs="http://open-collaboration-services.org/ns">
  434. <d:prop>
  435. ' . $properties . '
  436. </d:prop>
  437. </d:propfind>';
  438. $response = $client->request('PROPFIND', $this->makeSabrePath($user, $path), $body);
  439. $parsedResponse = $client->parseMultistatus($response['body']);
  440. return $parsedResponse;
  441. }
  442. /**
  443. * Returns the elements of a searc command
  444. * @param string $properties properties which needs to be included in the report
  445. * @param string $filterRules filter-rules to choose what needs to appear in the report
  446. */
  447. public function searchFile(string $user, ?string $properties = null, ?string $scope = null, ?string $condition = null) {
  448. $client = $this->getSabreClient($user);
  449. if ($properties === null) {
  450. $properties = '<oc:fileid /> <d:getlastmodified /> <d:getetag /> <d:getcontenttype /> <d:getcontentlength /> <nc:has-preview /> <oc:favorite /> <d:resourcetype />';
  451. }
  452. if ($condition === null) {
  453. $condition = '<d:and>
  454. <d:or>
  455. <d:eq>
  456. <d:prop>
  457. <d:getcontenttype/>
  458. </d:prop>
  459. <d:literal>image/png</d:literal>
  460. </d:eq>
  461. <d:eq>
  462. <d:prop>
  463. <d:getcontenttype/>
  464. </d:prop>
  465. <d:literal>image/jpeg</d:literal>
  466. </d:eq>
  467. <d:eq>
  468. <d:prop>
  469. <d:getcontenttype/>
  470. </d:prop>
  471. <d:literal>image/heic</d:literal>
  472. </d:eq>
  473. <d:eq>
  474. <d:prop>
  475. <d:getcontenttype/>
  476. </d:prop>
  477. <d:literal>video/mp4</d:literal>
  478. </d:eq>
  479. <d:eq>
  480. <d:prop>
  481. <d:getcontenttype/>
  482. </d:prop>
  483. <d:literal>video/quicktime</d:literal>
  484. </d:eq>
  485. </d:or>
  486. <d:eq>
  487. <d:prop>
  488. <oc:owner-id/>
  489. </d:prop>
  490. <d:literal>' . $user . '</d:literal>
  491. </d:eq>
  492. </d:and>';
  493. }
  494. if ($scope === null) {
  495. $scope = '<d:href>/files/' . $user . '</d:href><d:depth>infinity</d:depth>';
  496. }
  497. $body = '<?xml version="1.0" encoding="UTF-8"?>
  498. <d:searchrequest xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns" xmlns:ns="https://github.com/icewind1991/SearchDAV/ns" xmlns:ocs="http://open-collaboration-services.org/ns">
  499. <d:basicsearch>
  500. <d:select>
  501. <d:prop>' . $properties . '</d:prop>
  502. </d:select>
  503. <d:from><d:scope>' . $scope . '</d:scope></d:from>
  504. <d:where>' . $condition . '</d:where>
  505. <d:orderby>
  506. <d:order>
  507. <d:prop><d:getlastmodified/></d:prop>
  508. <d:descending/>
  509. </d:order>
  510. </d:orderby>
  511. <d:limit>
  512. <d:nresults>35</d:nresults>
  513. <ns:firstresult>0</ns:firstresult>
  514. </d:limit>
  515. </d:basicsearch>
  516. </d:searchrequest>';
  517. try {
  518. $this->response = $this->makeDavRequest($user, 'SEARCH', '', [
  519. 'Content-Type' => 'text/xml'
  520. ], $body, '');
  521. var_dump((string)$this->response->getBody());
  522. } catch (\GuzzleHttp\Exception\ServerException $e) {
  523. // 5xx responses cause a server exception
  524. $this->response = $e->getResponse();
  525. } catch (\GuzzleHttp\Exception\ClientException $e) {
  526. // 4xx responses cause a client exception
  527. $this->response = $e->getResponse();
  528. }
  529. }
  530. /* Returns the elements of a report command
  531. * @param string $user
  532. * @param string $path
  533. * @param string $properties properties which needs to be included in the report
  534. * @param string $filterRules filter-rules to choose what needs to appear in the report
  535. */
  536. public function reportFolder($user, $path, $properties, $filterRules) {
  537. $client = $this->getSabreClient($user);
  538. $body = '<?xml version="1.0" encoding="utf-8" ?>
  539. <oc:filter-files xmlns:a="DAV:" xmlns:oc="http://owncloud.org/ns" >
  540. <a:prop>
  541. ' . $properties . '
  542. </a:prop>
  543. <oc:filter-rules>
  544. ' . $filterRules . '
  545. </oc:filter-rules>
  546. </oc:filter-files>';
  547. $response = $client->request('REPORT', $this->makeSabrePath($user, $path), $body);
  548. $parsedResponse = $client->parseMultistatus($response['body']);
  549. return $parsedResponse;
  550. }
  551. public function makeSabrePath($user, $path, $type = 'files') {
  552. if ($type === 'files') {
  553. return $this->encodePath($this->getDavFilesPath($user) . $path);
  554. } else {
  555. return $this->encodePath($this->davPath . '/' . $type . '/' . $user . '/' . $path);
  556. }
  557. }
  558. public function getSabreClient($user) {
  559. $fullUrl = substr($this->baseUrl, 0, -4);
  560. $settings = [
  561. 'baseUri' => $fullUrl,
  562. 'userName' => $user,
  563. ];
  564. if ($user === 'admin') {
  565. $settings['password'] = $this->adminUser[1];
  566. } else {
  567. $settings['password'] = $this->regularUser;
  568. }
  569. $settings['authType'] = SClient::AUTH_BASIC;
  570. return new SClient($settings);
  571. }
  572. /**
  573. * @Then /^user "([^"]*)" should see following elements$/
  574. * @param string $user
  575. * @param \Behat\Gherkin\Node\TableNode|null $expectedElements
  576. */
  577. public function checkElementList($user, $expectedElements) {
  578. $elementList = $this->listFolder($user, '/', 3);
  579. if ($expectedElements instanceof \Behat\Gherkin\Node\TableNode) {
  580. $elementRows = $expectedElements->getRows();
  581. $elementsSimplified = $this->simplifyArray($elementRows);
  582. foreach ($elementsSimplified as $expectedElement) {
  583. $webdavPath = '/' . $this->getDavFilesPath($user) . $expectedElement;
  584. if (!array_key_exists($webdavPath, $elementList)) {
  585. Assert::fail("$webdavPath" . ' is not in propfind answer');
  586. }
  587. }
  588. }
  589. }
  590. /**
  591. * @When User :user uploads file :source to :destination
  592. * @param string $user
  593. * @param string $source
  594. * @param string $destination
  595. */
  596. public function userUploadsAFileTo($user, $source, $destination) {
  597. $file = \GuzzleHttp\Psr7\Utils::streamFor(fopen($source, 'r'));
  598. try {
  599. $this->response = $this->makeDavRequest($user, 'PUT', $destination, [], $file);
  600. } catch (\GuzzleHttp\Exception\ServerException $e) {
  601. // 5xx responses cause a server exception
  602. $this->response = $e->getResponse();
  603. } catch (\GuzzleHttp\Exception\ClientException $e) {
  604. // 4xx responses cause a client exception
  605. $this->response = $e->getResponse();
  606. }
  607. }
  608. /**
  609. * @When User :user adds a file of :bytes bytes to :destination
  610. * @param string $user
  611. * @param string $bytes
  612. * @param string $destination
  613. */
  614. public function userAddsAFileTo($user, $bytes, $destination) {
  615. $filename = 'filespecificSize.txt';
  616. $this->createFileSpecificSize($filename, $bytes);
  617. Assert::assertEquals(1, file_exists("work/$filename"));
  618. $this->userUploadsAFileTo($user, "work/$filename", $destination);
  619. $this->removeFile('work/', $filename);
  620. $expectedElements = new \Behat\Gherkin\Node\TableNode([["$destination"]]);
  621. $this->checkElementList($user, $expectedElements);
  622. }
  623. /**
  624. * @When User :user uploads file with content :content to :destination
  625. */
  626. public function userUploadsAFileWithContentTo($user, $content, $destination) {
  627. $file = \GuzzleHttp\Psr7\Utils::streamFor($content);
  628. try {
  629. $this->response = $this->makeDavRequest($user, 'PUT', $destination, [], $file);
  630. } catch (\GuzzleHttp\Exception\ServerException $e) {
  631. // 5xx responses cause a server exception
  632. $this->response = $e->getResponse();
  633. } catch (\GuzzleHttp\Exception\ClientException $e) {
  634. // 4xx responses cause a client exception
  635. $this->response = $e->getResponse();
  636. }
  637. }
  638. /**
  639. * @When /^User "([^"]*)" deletes (file|folder) "([^"]*)"$/
  640. * @param string $user
  641. * @param string $type
  642. * @param string $file
  643. */
  644. public function userDeletesFile($user, $type, $file) {
  645. try {
  646. $this->response = $this->makeDavRequest($user, 'DELETE', $file, []);
  647. } catch (\GuzzleHttp\Exception\ServerException $e) {
  648. // 5xx responses cause a server exception
  649. $this->response = $e->getResponse();
  650. } catch (\GuzzleHttp\Exception\ClientException $e) {
  651. // 4xx responses cause a client exception
  652. $this->response = $e->getResponse();
  653. }
  654. }
  655. /**
  656. * @Given User :user created a folder :destination
  657. * @param string $user
  658. * @param string $destination
  659. */
  660. public function userCreatedAFolder($user, $destination) {
  661. try {
  662. $destination = '/' . ltrim($destination, '/');
  663. $this->response = $this->makeDavRequest($user, 'MKCOL', $destination, []);
  664. } catch (\GuzzleHttp\Exception\ServerException $e) {
  665. // 5xx responses cause a server exception
  666. $this->response = $e->getResponse();
  667. } catch (\GuzzleHttp\Exception\ClientException $e) {
  668. // 4xx responses cause a client exception
  669. $this->response = $e->getResponse();
  670. }
  671. }
  672. /**
  673. * @Given user :user uploads bulked files :name1 with :content1 and :name2 with :content2 and :name3 with :content3
  674. * @param string $user
  675. * @param string $name1
  676. * @param string $content1
  677. * @param string $name2
  678. * @param string $content2
  679. * @param string $name3
  680. * @param string $content3
  681. */
  682. public function userUploadsBulkedFiles($user, $name1, $content1, $name2, $content2, $name3, $content3) {
  683. $boundary = 'boundary_azertyuiop';
  684. $body = '';
  685. $body .= '--' . $boundary . "\r\n";
  686. $body .= 'X-File-Path: ' . $name1 . "\r\n";
  687. $body .= "X-File-MD5: f6a6263167c92de8644ac998b3c4e4d1\r\n";
  688. $body .= "X-OC-Mtime: 1111111111\r\n";
  689. $body .= 'Content-Length: ' . strlen($content1) . "\r\n";
  690. $body .= "\r\n";
  691. $body .= $content1 . "\r\n";
  692. $body .= '--' . $boundary . "\r\n";
  693. $body .= 'X-File-Path: ' . $name2 . "\r\n";
  694. $body .= "X-File-MD5: 87c7d4068be07d390a1fffd21bf1e944\r\n";
  695. $body .= "X-OC-Mtime: 2222222222\r\n";
  696. $body .= 'Content-Length: ' . strlen($content2) . "\r\n";
  697. $body .= "\r\n";
  698. $body .= $content2 . "\r\n";
  699. $body .= '--' . $boundary . "\r\n";
  700. $body .= 'X-File-Path: ' . $name3 . "\r\n";
  701. $body .= "X-File-MD5: e86a1cf0678099986a901c79086f5617\r\n";
  702. $body .= "X-File-Mtime: 3333333333\r\n";
  703. $body .= 'Content-Length: ' . strlen($content3) . "\r\n";
  704. $body .= "\r\n";
  705. $body .= $content3 . "\r\n";
  706. $body .= '--' . $boundary . "--\r\n";
  707. $stream = fopen('php://temp', 'r+');
  708. fwrite($stream, $body);
  709. rewind($stream);
  710. $client = new GClient();
  711. $options = [
  712. 'auth' => [$user, $this->regularUser],
  713. 'headers' => [
  714. 'Content-Type' => 'multipart/related; boundary=' . $boundary,
  715. 'Content-Length' => (string)strlen($body),
  716. ],
  717. 'body' => $body
  718. ];
  719. return $client->request('POST', substr($this->baseUrl, 0, -4) . 'remote.php/dav/bulk', $options);
  720. }
  721. /**
  722. * @Given user :user creates a new chunking upload with id :id
  723. */
  724. public function userCreatesANewChunkingUploadWithId($user, $id) {
  725. $this->parts = [];
  726. $destination = '/uploads/' . $user . '/' . $id;
  727. $this->makeDavRequest($user, 'MKCOL', $destination, [], null, 'uploads');
  728. }
  729. /**
  730. * @Given user :user uploads new chunk file :num with :data to id :id
  731. */
  732. public function userUploadsNewChunkFileOfWithToId($user, $num, $data, $id) {
  733. $data = \GuzzleHttp\Psr7\Utils::streamFor($data);
  734. $destination = '/uploads/' . $user . '/' . $id . '/' . $num;
  735. $this->makeDavRequest($user, 'PUT', $destination, [], $data, 'uploads');
  736. }
  737. /**
  738. * @Given user :user moves new chunk file with id :id to :dest
  739. */
  740. public function userMovesNewChunkFileWithIdToMychunkedfile($user, $id, $dest) {
  741. $source = '/uploads/' . $user . '/' . $id . '/.file';
  742. $destination = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . $dest;
  743. $this->makeDavRequest($user, 'MOVE', $source, [
  744. 'Destination' => $destination
  745. ], null, 'uploads');
  746. }
  747. /**
  748. * @Then user :user moves new chunk file with id :id to :dest with size :size
  749. */
  750. public function userMovesNewChunkFileWithIdToMychunkedfileWithSize($user, $id, $dest, $size) {
  751. $source = '/uploads/' . $user . '/' . $id . '/.file';
  752. $destination = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . $dest;
  753. try {
  754. $this->response = $this->makeDavRequest($user, 'MOVE', $source, [
  755. 'Destination' => $destination,
  756. 'OC-Total-Length' => $size
  757. ], null, 'uploads');
  758. } catch (\GuzzleHttp\Exception\BadResponseException $ex) {
  759. $this->response = $ex->getResponse();
  760. }
  761. }
  762. /**
  763. * @Given user :user creates a new chunking v2 upload with id :id and destination :targetDestination
  764. */
  765. public function userCreatesANewChunkingv2UploadWithIdAndDestination($user, $id, $targetDestination) {
  766. $this->s3MultipartDestination = $this->getTargetDestination($user, $targetDestination);
  767. $this->newUploadId();
  768. $destination = '/uploads/' . $user . '/' . $this->getUploadId($id);
  769. $this->response = $this->makeDavRequest($user, 'MKCOL', $destination, [
  770. 'Destination' => $this->s3MultipartDestination,
  771. ], null, 'uploads');
  772. }
  773. /**
  774. * @Given user :user uploads new chunk v2 file :num to id :id
  775. */
  776. public function userUploadsNewChunkv2FileToIdAndDestination($user, $num, $id) {
  777. $data = \GuzzleHttp\Psr7\Utils::streamFor(fopen('/tmp/part-upload-' . $num, 'r'));
  778. $destination = '/uploads/' . $user . '/' . $this->getUploadId($id) . '/' . $num;
  779. $this->response = $this->makeDavRequest($user, 'PUT', $destination, [
  780. 'Destination' => $this->s3MultipartDestination
  781. ], $data, 'uploads');
  782. }
  783. /**
  784. * @Given user :user moves new chunk v2 file with id :id
  785. */
  786. public function userMovesNewChunkv2FileWithIdToMychunkedfileAndDestination($user, $id) {
  787. $source = '/uploads/' . $user . '/' . $this->getUploadId($id) . '/.file';
  788. try {
  789. $this->response = $this->makeDavRequest($user, 'MOVE', $source, [
  790. 'Destination' => $this->s3MultipartDestination,
  791. ], null, 'uploads');
  792. } catch (\GuzzleHttp\Exception\ServerException $e) {
  793. // 5xx responses cause a server exception
  794. $this->response = $e->getResponse();
  795. } catch (\GuzzleHttp\Exception\ClientException $e) {
  796. // 4xx responses cause a client exception
  797. $this->response = $e->getResponse();
  798. }
  799. }
  800. private function getTargetDestination(string $user, string $destination): string {
  801. return substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . $destination;
  802. }
  803. private function getUploadId(string $id): string {
  804. return $id . '-' . $this->uploadId;
  805. }
  806. private function newUploadId() {
  807. $this->uploadId = (string)time();
  808. }
  809. /**
  810. * @Given /^Downloading file "([^"]*)" as "([^"]*)"$/
  811. */
  812. public function downloadingFileAs($fileName, $user) {
  813. try {
  814. $this->response = $this->makeDavRequest($user, 'GET', $fileName, []);
  815. } catch (\GuzzleHttp\Exception\ServerException $e) {
  816. // 5xx responses cause a server exception
  817. $this->response = $e->getResponse();
  818. } catch (\GuzzleHttp\Exception\ClientException $e) {
  819. // 4xx responses cause a client exception
  820. $this->response = $e->getResponse();
  821. }
  822. }
  823. /**
  824. * URL encodes the given path but keeps the slashes
  825. *
  826. * @param string $path to encode
  827. * @return string encoded path
  828. */
  829. private function encodePath($path) {
  830. // slashes need to stay
  831. return str_replace('%2F', '/', rawurlencode($path));
  832. }
  833. /**
  834. * @When user :user favorites element :path
  835. */
  836. public function userFavoritesElement($user, $path) {
  837. $this->response = $this->changeFavStateOfAnElement($user, $path, 1, 0, null);
  838. }
  839. /**
  840. * @When user :user unfavorites element :path
  841. */
  842. public function userUnfavoritesElement($user, $path) {
  843. $this->response = $this->changeFavStateOfAnElement($user, $path, 0, 0, null);
  844. }
  845. /*Set the elements of a proppatch, $folderDepth requires 1 to see elements without children*/
  846. public function changeFavStateOfAnElement($user, $path, $favOrUnfav, $folderDepth, $properties = null) {
  847. $fullUrl = substr($this->baseUrl, 0, -4);
  848. $settings = [
  849. 'baseUri' => $fullUrl,
  850. 'userName' => $user,
  851. ];
  852. if ($user === 'admin') {
  853. $settings['password'] = $this->adminUser[1];
  854. } else {
  855. $settings['password'] = $this->regularUser;
  856. }
  857. $settings['authType'] = SClient::AUTH_BASIC;
  858. $client = new SClient($settings);
  859. if (!$properties) {
  860. $properties = [
  861. '{http://owncloud.org/ns}favorite' => $favOrUnfav
  862. ];
  863. }
  864. $response = $client->proppatch($this->getDavFilesPath($user) . $path, $properties, $folderDepth);
  865. return $response;
  866. }
  867. /**
  868. * @Given user :user stores etag of element :path
  869. */
  870. public function userStoresEtagOfElement($user, $path) {
  871. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{DAV:}getetag']]);
  872. $this->asGetsPropertiesOfFolderWith($user, 'entry', $path, $propertiesTable);
  873. $pathETAG[$path] = $this->response['{DAV:}getetag'];
  874. $this->storedETAG[$user] = $pathETAG;
  875. }
  876. /**
  877. * @Then etag of element :path of user :user has not changed
  878. */
  879. public function checkIfETAGHasNotChanged($path, $user) {
  880. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{DAV:}getetag']]);
  881. $this->asGetsPropertiesOfFolderWith($user, 'entry', $path, $propertiesTable);
  882. Assert::assertEquals($this->response['{DAV:}getetag'], $this->storedETAG[$user][$path]);
  883. }
  884. /**
  885. * @Then etag of element :path of user :user has changed
  886. */
  887. public function checkIfETAGHasChanged($path, $user) {
  888. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{DAV:}getetag']]);
  889. $this->asGetsPropertiesOfFolderWith($user, 'entry', $path, $propertiesTable);
  890. Assert::assertNotEquals($this->response['{DAV:}getetag'], $this->storedETAG[$user][$path]);
  891. }
  892. /**
  893. * @When Connecting to dav endpoint
  894. */
  895. public function connectingToDavEndpoint() {
  896. try {
  897. $this->response = $this->makeDavRequest(null, 'PROPFIND', '', []);
  898. } catch (\GuzzleHttp\Exception\ClientException $e) {
  899. $this->response = $e->getResponse();
  900. }
  901. }
  902. /**
  903. * @When Requesting share note on dav endpoint
  904. */
  905. public function requestingShareNote() {
  906. $propfind = '<d:propfind xmlns:d="DAV:" xmlns:nc="http://nextcloud.org/ns"><d:prop><nc:note /></d:prop></d:propfind>';
  907. if (count($this->lastShareData->data->element) > 0) {
  908. $token = $this->lastShareData->data[0]->token;
  909. } else {
  910. $token = $this->lastShareData->data->token;
  911. }
  912. try {
  913. $this->response = $this->makeDavRequest('', 'PROPFIND', $token, [], $propfind);
  914. } catch (\GuzzleHttp\Exception\ClientException $e) {
  915. $this->response = $e->getResponse();
  916. }
  917. }
  918. /**
  919. * @Then there are no duplicate headers
  920. */
  921. public function thereAreNoDuplicateHeaders() {
  922. $headers = $this->response->getHeaders();
  923. foreach ($headers as $headerName => $headerValues) {
  924. // if a header has multiple values, they must be different
  925. if (count($headerValues) > 1 && count(array_unique($headerValues)) < count($headerValues)) {
  926. throw new \Exception('Duplicate header found: ' . $headerName);
  927. }
  928. }
  929. }
  930. /**
  931. * @Then /^user "([^"]*)" in folder "([^"]*)" should have favorited the following elements$/
  932. * @param string $user
  933. * @param string $folder
  934. * @param \Behat\Gherkin\Node\TableNode|null $expectedElements
  935. */
  936. public function checkFavoritedElements($user, $folder, $expectedElements) {
  937. $elementList = $this->reportFolder($user,
  938. $folder,
  939. '<oc:favorite/>',
  940. '<oc:favorite>1</oc:favorite>');
  941. if ($expectedElements instanceof \Behat\Gherkin\Node\TableNode) {
  942. $elementRows = $expectedElements->getRows();
  943. $elementsSimplified = $this->simplifyArray($elementRows);
  944. foreach ($elementsSimplified as $expectedElement) {
  945. $webdavPath = '/' . $this->getDavFilesPath($user) . $expectedElement;
  946. if (!array_key_exists($webdavPath, $elementList)) {
  947. Assert::fail("$webdavPath" . ' is not in report answer');
  948. }
  949. }
  950. }
  951. }
  952. /**
  953. * @When /^User "([^"]*)" deletes everything from folder "([^"]*)"$/
  954. * @param string $user
  955. * @param string $folder
  956. */
  957. public function userDeletesEverythingInFolder($user, $folder) {
  958. $elementList = $this->listFolder($user, $folder, 1);
  959. $elementListKeys = array_keys($elementList);
  960. array_shift($elementListKeys);
  961. $davPrefix = '/' . $this->getDavFilesPath($user);
  962. foreach ($elementListKeys as $element) {
  963. if (substr($element, 0, strlen($davPrefix)) == $davPrefix) {
  964. $element = substr($element, strlen($davPrefix));
  965. }
  966. $this->userDeletesFile($user, 'element', $element);
  967. }
  968. }
  969. /**
  970. * @param string $user
  971. * @param string $path
  972. * @return int
  973. */
  974. private function getFileIdForPath($user, $path) {
  975. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{http://owncloud.org/ns}fileid']]);
  976. $this->asGetsPropertiesOfFolderWith($user, 'file', $path, $propertiesTable);
  977. return (int)$this->response['{http://owncloud.org/ns}fileid'];
  978. }
  979. /**
  980. * @Given /^User "([^"]*)" stores id of file "([^"]*)"$/
  981. * @param string $user
  982. * @param string $path
  983. */
  984. public function userStoresFileIdForPath($user, $path) {
  985. $this->storedFileID = $this->getFileIdForPath($user, $path);
  986. }
  987. /**
  988. * @Given /^User "([^"]*)" checks id of file "([^"]*)"$/
  989. * @param string $user
  990. * @param string $path
  991. */
  992. public function userChecksFileIdForPath($user, $path) {
  993. $currentFileID = $this->getFileIdForPath($user, $path);
  994. Assert::assertEquals($currentFileID, $this->storedFileID);
  995. }
  996. /**
  997. * @Given /^user "([^"]*)" creates a file locally with "([^"]*)" x 5 MB chunks$/
  998. */
  999. public function userCreatesAFileLocallyWithChunks($arg1, $chunks) {
  1000. $this->parts = [];
  1001. for ($i = 1;$i <= (int)$chunks;$i++) {
  1002. $randomletter = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 1);
  1003. file_put_contents('/tmp/part-upload-' . $i, str_repeat($randomletter, 5 * 1024 * 1024));
  1004. $this->parts[] = '/tmp/part-upload-' . $i;
  1005. }
  1006. }
  1007. /**
  1008. * @Given user :user creates the chunk :id with a size of :size MB
  1009. */
  1010. public function userCreatesAChunk($user, $id, $size) {
  1011. $randomletter = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 1);
  1012. file_put_contents('/tmp/part-upload-' . $id, str_repeat($randomletter, (int)$size * 1024 * 1024));
  1013. $this->parts[] = '/tmp/part-upload-' . $id;
  1014. }
  1015. /**
  1016. * @Then /^Downloaded content should be the created file$/
  1017. */
  1018. public function downloadedContentShouldBeTheCreatedFile() {
  1019. $content = '';
  1020. sort($this->parts);
  1021. foreach ($this->parts as $part) {
  1022. $content .= file_get_contents($part);
  1023. }
  1024. Assert::assertEquals($content, (string)$this->response->getBody());
  1025. }
  1026. /**
  1027. * @Then /^the S3 multipart upload was successful with status "([^"]*)"$/
  1028. */
  1029. public function theSmultipartUploadWasSuccessful($status) {
  1030. Assert::assertEquals((int)$status, $this->response->getStatusCode());
  1031. }
  1032. /**
  1033. * @Then /^the upload should fail on object storage$/
  1034. */
  1035. public function theUploadShouldFailOnObjectStorage() {
  1036. $descriptor = [
  1037. 0 => ['pipe', 'r'],
  1038. 1 => ['pipe', 'w'],
  1039. 2 => ['pipe', 'w'],
  1040. ];
  1041. $process = proc_open('php occ config:system:get objectstore --no-ansi', $descriptor, $pipes, '../../');
  1042. $lastCode = proc_close($process);
  1043. if ($lastCode === 0) {
  1044. $this->theHTTPStatusCodeShouldBe(500);
  1045. }
  1046. }
  1047. /**
  1048. * @return array
  1049. * @throws Exception
  1050. */
  1051. private function convertResponseToDavSingleEntry(): array {
  1052. $results = $this->convertResponseToDavEntries();
  1053. if (count($results) > 1) {
  1054. throw new \Exception('result is empty or contain more than one (1) entry');
  1055. }
  1056. return array_shift($results);
  1057. }
  1058. /**
  1059. * @return array
  1060. */
  1061. private function convertResponseToDavEntries(): array {
  1062. $client = $this->getSabreClient($this->currentUser);
  1063. $parsedResponse = $client->parseMultiStatus((string)$this->response->getBody());
  1064. $results = [];
  1065. foreach ($parsedResponse as $href => $statusList) {
  1066. $results[$href] = $statusList[200] ?? [];
  1067. }
  1068. return $results;
  1069. }
  1070. }