WebDav.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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 file :fileName
  216. * @param string $fileName
  217. */
  218. public function downloadingFile($fileName) {
  219. try {
  220. $this->response = $this->makeDavRequest($this->currentUser, 'GET', $fileName, []);
  221. } catch (\GuzzleHttp\Exception\ClientException $e) {
  222. $this->response = $e->getResponse();
  223. }
  224. }
  225. /**
  226. * @Then Downloaded content should start with :start
  227. * @param int $start
  228. * @throws \Exception
  229. */
  230. public function downloadedContentShouldStartWith($start) {
  231. if (strpos($this->response->getBody()->getContents(), $start) !== 0) {
  232. throw new \Exception(
  233. sprintf(
  234. "Expected '%s', got '%s'",
  235. $start,
  236. $this->response->getBody()->getContents()
  237. )
  238. );
  239. }
  240. }
  241. /**
  242. * @Then /^as "([^"]*)" gets properties of (file|folder|entry) "([^"]*)" with$/
  243. * @param string $user
  244. * @param string $elementType
  245. * @param string $path
  246. * @param \Behat\Gherkin\Node\TableNode|null $propertiesTable
  247. */
  248. public function asGetsPropertiesOfFolderWith($user, $elementType, $path, $propertiesTable) {
  249. $properties = null;
  250. if ($propertiesTable instanceof \Behat\Gherkin\Node\TableNode) {
  251. foreach ($propertiesTable->getRows() as $row) {
  252. $properties[] = $row[0];
  253. }
  254. }
  255. $this->response = $this->listFolder($user, $path, 0, $properties);
  256. }
  257. /**
  258. * @Then /^as "([^"]*)" the (file|folder|entry) "([^"]*)" does not exist$/
  259. * @param string $user
  260. * @param string $entry
  261. * @param string $path
  262. * @param \Behat\Gherkin\Node\TableNode|null $propertiesTable
  263. */
  264. public function asTheFileOrFolderDoesNotExist($user, $entry, $path) {
  265. $client = $this->getSabreClient($user);
  266. $response = $client->request('HEAD', $this->makeSabrePath($user, $path));
  267. if ($response['statusCode'] !== 404) {
  268. throw new \Exception($entry . ' "' . $path . '" expected to not exist (status code ' . $response['statusCode'] . ', expected 404)');
  269. }
  270. return $response;
  271. }
  272. /**
  273. * @Then /^as "([^"]*)" the (file|folder|entry) "([^"]*)" exists$/
  274. * @param string $user
  275. * @param string $entry
  276. * @param string $path
  277. */
  278. public function asTheFileOrFolderExists($user, $entry, $path) {
  279. $this->response = $this->listFolder($user, $path, 0);
  280. }
  281. /**
  282. * @Then the response should be empty
  283. * @throws \Exception
  284. */
  285. public function theResponseShouldBeEmpty(): void {
  286. $response = ($this->response instanceof ResponseInterface) ? $this->convertResponseToDavEntries() : $this->response;
  287. if ($response === []) {
  288. return;
  289. }
  290. throw new \Exception('response is not empty');
  291. }
  292. /**
  293. * @Then the single response should contain a property :key with value :value
  294. * @param string $key
  295. * @param string $expectedValue
  296. * @throws \Exception
  297. */
  298. public function theSingleResponseShouldContainAPropertyWithValue($key, $expectedValue) {
  299. $response = ($this->response instanceof ResponseInterface) ? $this->convertResponseToDavSingleEntry() : $this->response;
  300. if (!array_key_exists($key, $response)) {
  301. throw new \Exception("Cannot find property \"$key\" with \"$expectedValue\"");
  302. }
  303. $value = $response[$key];
  304. if ($value instanceof ResourceType) {
  305. $value = $value->getValue();
  306. if (empty($value)) {
  307. $value = '';
  308. } else {
  309. $value = $value[0];
  310. }
  311. }
  312. if ($value != $expectedValue) {
  313. throw new \Exception("Property \"$key\" found with value \"$value\", expected \"$expectedValue\"");
  314. }
  315. }
  316. /**
  317. * @Then the response should contain a share-types property with
  318. */
  319. public function theResponseShouldContainAShareTypesPropertyWith($table) {
  320. $keys = $this->response;
  321. if (!array_key_exists('{http://owncloud.org/ns}share-types', $keys)) {
  322. throw new \Exception('Cannot find property "{http://owncloud.org/ns}share-types"');
  323. }
  324. $foundTypes = [];
  325. $data = $keys['{http://owncloud.org/ns}share-types'];
  326. foreach ($data as $item) {
  327. if ($item['name'] !== '{http://owncloud.org/ns}share-type') {
  328. throw new \Exception('Invalid property found: "' . $item['name'] . '"');
  329. }
  330. $foundTypes[] = $item['value'];
  331. }
  332. foreach ($table->getRows() as $row) {
  333. $key = array_search($row[0], $foundTypes);
  334. if ($key === false) {
  335. throw new \Exception('Expected type ' . $row[0] . ' not found');
  336. }
  337. unset($foundTypes[$key]);
  338. }
  339. if ($foundTypes !== []) {
  340. throw new \Exception('Found more share types then specified: ' . $foundTypes);
  341. }
  342. }
  343. /**
  344. * @Then the response should contain an empty property :property
  345. * @param string $property
  346. * @throws \Exception
  347. */
  348. public function theResponseShouldContainAnEmptyProperty($property) {
  349. $properties = $this->response;
  350. if (!array_key_exists($property, $properties)) {
  351. throw new \Exception("Cannot find property \"$property\"");
  352. }
  353. if ($properties[$property] !== null) {
  354. throw new \Exception("Property \"$property\" is not empty");
  355. }
  356. }
  357. /*Returns the elements of a propfind, $folderDepth requires 1 to see elements without children*/
  358. public function listFolder($user, $path, $folderDepth, $properties = null) {
  359. $client = $this->getSabreClient($user);
  360. if (!$properties) {
  361. $properties = [
  362. '{DAV:}getetag'
  363. ];
  364. }
  365. $response = $client->propfind($this->makeSabrePath($user, $path), $properties, $folderDepth);
  366. return $response;
  367. }
  368. /**
  369. * Returns the elements of a profind command
  370. * @param string $properties properties which needs to be included in the report
  371. * @param string $filterRules filter-rules to choose what needs to appear in the report
  372. */
  373. public function propfindFile(string $user, string $path, string $properties = '') {
  374. $client = $this->getSabreClient($user);
  375. $body = '<?xml version="1.0" encoding="utf-8" ?>
  376. <d:propfind xmlns:d="DAV:"
  377. xmlns:oc="http://owncloud.org/ns"
  378. xmlns:nc="http://nextcloud.org/ns"
  379. xmlns:ocs="http://open-collaboration-services.org/ns">
  380. <d:prop>
  381. ' . $properties . '
  382. </d:prop>
  383. </d:propfind>';
  384. $response = $client->request('PROPFIND', $this->makeSabrePath($user, $path), $body);
  385. $parsedResponse = $client->parseMultistatus($response['body']);
  386. return $parsedResponse;
  387. }
  388. /**
  389. * Returns the elements of a searc command
  390. * @param string $properties properties which needs to be included in the report
  391. * @param string $filterRules filter-rules to choose what needs to appear in the report
  392. */
  393. public function searchFile(string $user, ?string $properties = null, ?string $scope = null, ?string $condition = null) {
  394. $client = $this->getSabreClient($user);
  395. if ($properties === null) {
  396. $properties = '<oc:fileid /> <d:getlastmodified /> <d:getetag /> <d:getcontenttype /> <d:getcontentlength /> <nc:has-preview /> <oc:favorite /> <d:resourcetype />';
  397. }
  398. if ($condition === null) {
  399. $condition = '<d:and>
  400. <d:or>
  401. <d:eq>
  402. <d:prop>
  403. <d:getcontenttype/>
  404. </d:prop>
  405. <d:literal>image/png</d:literal>
  406. </d:eq>
  407. <d:eq>
  408. <d:prop>
  409. <d:getcontenttype/>
  410. </d:prop>
  411. <d:literal>image/jpeg</d:literal>
  412. </d:eq>
  413. <d:eq>
  414. <d:prop>
  415. <d:getcontenttype/>
  416. </d:prop>
  417. <d:literal>image/heic</d:literal>
  418. </d:eq>
  419. <d:eq>
  420. <d:prop>
  421. <d:getcontenttype/>
  422. </d:prop>
  423. <d:literal>video/mp4</d:literal>
  424. </d:eq>
  425. <d:eq>
  426. <d:prop>
  427. <d:getcontenttype/>
  428. </d:prop>
  429. <d:literal>video/quicktime</d:literal>
  430. </d:eq>
  431. </d:or>
  432. <d:eq>
  433. <d:prop>
  434. <oc:owner-id/>
  435. </d:prop>
  436. <d:literal>' . $user . '</d:literal>
  437. </d:eq>
  438. </d:and>';
  439. }
  440. if ($scope === null) {
  441. $scope = '<d:href>/files/' . $user . '</d:href><d:depth>infinity</d:depth>';
  442. }
  443. $body = '<?xml version="1.0" encoding="UTF-8"?>
  444. <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">
  445. <d:basicsearch>
  446. <d:select>
  447. <d:prop>' . $properties . '</d:prop>
  448. </d:select>
  449. <d:from><d:scope>' . $scope . '</d:scope></d:from>
  450. <d:where>' . $condition . '</d:where>
  451. <d:orderby>
  452. <d:order>
  453. <d:prop><d:getlastmodified/></d:prop>
  454. <d:descending/>
  455. </d:order>
  456. </d:orderby>
  457. <d:limit>
  458. <d:nresults>35</d:nresults>
  459. <ns:firstresult>0</ns:firstresult>
  460. </d:limit>
  461. </d:basicsearch>
  462. </d:searchrequest>';
  463. try {
  464. $this->response = $this->makeDavRequest($user, 'SEARCH', '', [
  465. 'Content-Type' => 'text/xml'
  466. ], $body, '');
  467. var_dump((string)$this->response->getBody());
  468. } catch (\GuzzleHttp\Exception\ServerException $e) {
  469. // 5xx responses cause a server exception
  470. $this->response = $e->getResponse();
  471. } catch (\GuzzleHttp\Exception\ClientException $e) {
  472. // 4xx responses cause a client exception
  473. $this->response = $e->getResponse();
  474. }
  475. }
  476. /* Returns the elements of a report command
  477. * @param string $user
  478. * @param string $path
  479. * @param string $properties properties which needs to be included in the report
  480. * @param string $filterRules filter-rules to choose what needs to appear in the report
  481. */
  482. public function reportFolder($user, $path, $properties, $filterRules) {
  483. $client = $this->getSabreClient($user);
  484. $body = '<?xml version="1.0" encoding="utf-8" ?>
  485. <oc:filter-files xmlns:a="DAV:" xmlns:oc="http://owncloud.org/ns" >
  486. <a:prop>
  487. ' . $properties . '
  488. </a:prop>
  489. <oc:filter-rules>
  490. ' . $filterRules . '
  491. </oc:filter-rules>
  492. </oc:filter-files>';
  493. $response = $client->request('REPORT', $this->makeSabrePath($user, $path), $body);
  494. $parsedResponse = $client->parseMultistatus($response['body']);
  495. return $parsedResponse;
  496. }
  497. public function makeSabrePath($user, $path, $type = 'files') {
  498. if ($type === 'files') {
  499. return $this->encodePath($this->getDavFilesPath($user) . $path);
  500. } else {
  501. return $this->encodePath($this->davPath . '/' . $type . '/' . $user . '/' . $path);
  502. }
  503. }
  504. public function getSabreClient($user) {
  505. $fullUrl = substr($this->baseUrl, 0, -4);
  506. $settings = [
  507. 'baseUri' => $fullUrl,
  508. 'userName' => $user,
  509. ];
  510. if ($user === 'admin') {
  511. $settings['password'] = $this->adminUser[1];
  512. } else {
  513. $settings['password'] = $this->regularUser;
  514. }
  515. $settings['authType'] = SClient::AUTH_BASIC;
  516. return new SClient($settings);
  517. }
  518. /**
  519. * @Then /^user "([^"]*)" should see following elements$/
  520. * @param string $user
  521. * @param \Behat\Gherkin\Node\TableNode|null $expectedElements
  522. */
  523. public function checkElementList($user, $expectedElements) {
  524. $elementList = $this->listFolder($user, '/', 3);
  525. if ($expectedElements instanceof \Behat\Gherkin\Node\TableNode) {
  526. $elementRows = $expectedElements->getRows();
  527. $elementsSimplified = $this->simplifyArray($elementRows);
  528. foreach ($elementsSimplified as $expectedElement) {
  529. $webdavPath = '/' . $this->getDavFilesPath($user) . $expectedElement;
  530. if (!array_key_exists($webdavPath, $elementList)) {
  531. Assert::fail("$webdavPath" . ' is not in propfind answer');
  532. }
  533. }
  534. }
  535. }
  536. /**
  537. * @When User :user uploads file :source to :destination
  538. * @param string $user
  539. * @param string $source
  540. * @param string $destination
  541. */
  542. public function userUploadsAFileTo($user, $source, $destination) {
  543. $file = \GuzzleHttp\Psr7\Utils::streamFor(fopen($source, 'r'));
  544. try {
  545. $this->response = $this->makeDavRequest($user, 'PUT', $destination, [], $file);
  546. } catch (\GuzzleHttp\Exception\ServerException $e) {
  547. // 5xx responses cause a server exception
  548. $this->response = $e->getResponse();
  549. } catch (\GuzzleHttp\Exception\ClientException $e) {
  550. // 4xx responses cause a client exception
  551. $this->response = $e->getResponse();
  552. }
  553. }
  554. /**
  555. * @When User :user adds a file of :bytes bytes to :destination
  556. * @param string $user
  557. * @param string $bytes
  558. * @param string $destination
  559. */
  560. public function userAddsAFileTo($user, $bytes, $destination) {
  561. $filename = 'filespecificSize.txt';
  562. $this->createFileSpecificSize($filename, $bytes);
  563. Assert::assertEquals(1, file_exists("work/$filename"));
  564. $this->userUploadsAFileTo($user, "work/$filename", $destination);
  565. $this->removeFile('work/', $filename);
  566. $expectedElements = new \Behat\Gherkin\Node\TableNode([["$destination"]]);
  567. $this->checkElementList($user, $expectedElements);
  568. }
  569. /**
  570. * @When User :user uploads file with content :content to :destination
  571. */
  572. public function userUploadsAFileWithContentTo($user, $content, $destination) {
  573. $file = \GuzzleHttp\Psr7\Utils::streamFor($content);
  574. try {
  575. $this->response = $this->makeDavRequest($user, 'PUT', $destination, [], $file);
  576. } catch (\GuzzleHttp\Exception\ServerException $e) {
  577. // 5xx responses cause a server exception
  578. $this->response = $e->getResponse();
  579. } catch (\GuzzleHttp\Exception\ClientException $e) {
  580. // 4xx responses cause a client exception
  581. $this->response = $e->getResponse();
  582. }
  583. }
  584. /**
  585. * @When /^User "([^"]*)" deletes (file|folder) "([^"]*)"$/
  586. * @param string $user
  587. * @param string $type
  588. * @param string $file
  589. */
  590. public function userDeletesFile($user, $type, $file) {
  591. try {
  592. $this->response = $this->makeDavRequest($user, 'DELETE', $file, []);
  593. } catch (\GuzzleHttp\Exception\ServerException $e) {
  594. // 5xx responses cause a server exception
  595. $this->response = $e->getResponse();
  596. } catch (\GuzzleHttp\Exception\ClientException $e) {
  597. // 4xx responses cause a client exception
  598. $this->response = $e->getResponse();
  599. }
  600. }
  601. /**
  602. * @Given User :user created a folder :destination
  603. * @param string $user
  604. * @param string $destination
  605. */
  606. public function userCreatedAFolder($user, $destination) {
  607. try {
  608. $destination = '/' . ltrim($destination, '/');
  609. $this->response = $this->makeDavRequest($user, 'MKCOL', $destination, []);
  610. } catch (\GuzzleHttp\Exception\ServerException $e) {
  611. // 5xx responses cause a server exception
  612. $this->response = $e->getResponse();
  613. } catch (\GuzzleHttp\Exception\ClientException $e) {
  614. // 4xx responses cause a client exception
  615. $this->response = $e->getResponse();
  616. }
  617. }
  618. /**
  619. * @Given user :user uploads bulked files :name1 with :content1 and :name2 with :content2 and :name3 with :content3
  620. * @param string $user
  621. * @param string $name1
  622. * @param string $content1
  623. * @param string $name2
  624. * @param string $content2
  625. * @param string $name3
  626. * @param string $content3
  627. */
  628. public function userUploadsBulkedFiles($user, $name1, $content1, $name2, $content2, $name3, $content3) {
  629. $boundary = 'boundary_azertyuiop';
  630. $body = '';
  631. $body .= '--'.$boundary."\r\n";
  632. $body .= 'X-File-Path: '.$name1."\r\n";
  633. $body .= "X-File-MD5: f6a6263167c92de8644ac998b3c4e4d1\r\n";
  634. $body .= "X-OC-Mtime: 1111111111\r\n";
  635. $body .= 'Content-Length: '.strlen($content1)."\r\n";
  636. $body .= "\r\n";
  637. $body .= $content1."\r\n";
  638. $body .= '--'.$boundary."\r\n";
  639. $body .= 'X-File-Path: '.$name2."\r\n";
  640. $body .= "X-File-MD5: 87c7d4068be07d390a1fffd21bf1e944\r\n";
  641. $body .= "X-OC-Mtime: 2222222222\r\n";
  642. $body .= 'Content-Length: '.strlen($content2)."\r\n";
  643. $body .= "\r\n";
  644. $body .= $content2."\r\n";
  645. $body .= '--'.$boundary."\r\n";
  646. $body .= 'X-File-Path: '.$name3."\r\n";
  647. $body .= "X-File-MD5: e86a1cf0678099986a901c79086f5617\r\n";
  648. $body .= "X-File-Mtime: 3333333333\r\n";
  649. $body .= 'Content-Length: '.strlen($content3)."\r\n";
  650. $body .= "\r\n";
  651. $body .= $content3."\r\n";
  652. $body .= '--'.$boundary."--\r\n";
  653. $stream = fopen('php://temp', 'r+');
  654. fwrite($stream, $body);
  655. rewind($stream);
  656. $client = new GClient();
  657. $options = [
  658. 'auth' => [$user, $this->regularUser],
  659. 'headers' => [
  660. 'Content-Type' => 'multipart/related; boundary='.$boundary,
  661. 'Content-Length' => (string)strlen($body),
  662. ],
  663. 'body' => $body
  664. ];
  665. return $client->request('POST', substr($this->baseUrl, 0, -4) . 'remote.php/dav/bulk', $options);
  666. }
  667. /**
  668. * @Given user :user creates a new chunking upload with id :id
  669. */
  670. public function userCreatesANewChunkingUploadWithId($user, $id) {
  671. $this->parts = [];
  672. $destination = '/uploads/' . $user . '/' . $id;
  673. $this->makeDavRequest($user, 'MKCOL', $destination, [], null, 'uploads');
  674. }
  675. /**
  676. * @Given user :user uploads new chunk file :num with :data to id :id
  677. */
  678. public function userUploadsNewChunkFileOfWithToId($user, $num, $data, $id) {
  679. $data = \GuzzleHttp\Psr7\Utils::streamFor($data);
  680. $destination = '/uploads/' . $user . '/' . $id . '/' . $num;
  681. $this->makeDavRequest($user, 'PUT', $destination, [], $data, 'uploads');
  682. }
  683. /**
  684. * @Given user :user moves new chunk file with id :id to :dest
  685. */
  686. public function userMovesNewChunkFileWithIdToMychunkedfile($user, $id, $dest) {
  687. $source = '/uploads/' . $user . '/' . $id . '/.file';
  688. $destination = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . $dest;
  689. $this->makeDavRequest($user, 'MOVE', $source, [
  690. 'Destination' => $destination
  691. ], null, 'uploads');
  692. }
  693. /**
  694. * @Then user :user moves new chunk file with id :id to :dest with size :size
  695. */
  696. public function userMovesNewChunkFileWithIdToMychunkedfileWithSize($user, $id, $dest, $size) {
  697. $source = '/uploads/' . $user . '/' . $id . '/.file';
  698. $destination = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . $dest;
  699. try {
  700. $this->response = $this->makeDavRequest($user, 'MOVE', $source, [
  701. 'Destination' => $destination,
  702. 'OC-Total-Length' => $size
  703. ], null, 'uploads');
  704. } catch (\GuzzleHttp\Exception\BadResponseException $ex) {
  705. $this->response = $ex->getResponse();
  706. }
  707. }
  708. /**
  709. * @Given user :user creates a new chunking v2 upload with id :id and destination :targetDestination
  710. */
  711. public function userCreatesANewChunkingv2UploadWithIdAndDestination($user, $id, $targetDestination) {
  712. $this->s3MultipartDestination = $this->getTargetDestination($user, $targetDestination);
  713. $this->newUploadId();
  714. $destination = '/uploads/' . $user . '/' . $this->getUploadId($id);
  715. $this->response = $this->makeDavRequest($user, 'MKCOL', $destination, [
  716. 'Destination' => $this->s3MultipartDestination,
  717. ], null, 'uploads');
  718. }
  719. /**
  720. * @Given user :user uploads new chunk v2 file :num to id :id
  721. */
  722. public function userUploadsNewChunkv2FileToIdAndDestination($user, $num, $id) {
  723. $data = \GuzzleHttp\Psr7\Utils::streamFor(fopen('/tmp/part-upload-' . $num, 'r'));
  724. $destination = '/uploads/' . $user . '/' . $this->getUploadId($id) . '/' . $num;
  725. $this->response = $this->makeDavRequest($user, 'PUT', $destination, [
  726. 'Destination' => $this->s3MultipartDestination
  727. ], $data, 'uploads');
  728. }
  729. /**
  730. * @Given user :user moves new chunk v2 file with id :id
  731. */
  732. public function userMovesNewChunkv2FileWithIdToMychunkedfileAndDestination($user, $id) {
  733. $source = '/uploads/' . $user . '/' . $this->getUploadId($id) . '/.file';
  734. try {
  735. $this->response = $this->makeDavRequest($user, 'MOVE', $source, [
  736. 'Destination' => $this->s3MultipartDestination,
  737. ], null, 'uploads');
  738. } catch (\GuzzleHttp\Exception\ServerException $e) {
  739. // 5xx responses cause a server exception
  740. $this->response = $e->getResponse();
  741. } catch (\GuzzleHttp\Exception\ClientException $e) {
  742. // 4xx responses cause a client exception
  743. $this->response = $e->getResponse();
  744. }
  745. }
  746. private function getTargetDestination(string $user, string $destination): string {
  747. return substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . $destination;
  748. }
  749. private function getUploadId(string $id): string {
  750. return $id . '-' . $this->uploadId;
  751. }
  752. private function newUploadId() {
  753. $this->uploadId = (string)time();
  754. }
  755. /**
  756. * @Given /^Downloading file "([^"]*)" as "([^"]*)"$/
  757. */
  758. public function downloadingFileAs($fileName, $user) {
  759. try {
  760. $this->response = $this->makeDavRequest($user, 'GET', $fileName, []);
  761. } catch (\GuzzleHttp\Exception\ServerException $e) {
  762. // 5xx responses cause a server exception
  763. $this->response = $e->getResponse();
  764. } catch (\GuzzleHttp\Exception\ClientException $e) {
  765. // 4xx responses cause a client exception
  766. $this->response = $e->getResponse();
  767. }
  768. }
  769. /**
  770. * URL encodes the given path but keeps the slashes
  771. *
  772. * @param string $path to encode
  773. * @return string encoded path
  774. */
  775. private function encodePath($path) {
  776. // slashes need to stay
  777. return str_replace('%2F', '/', rawurlencode($path));
  778. }
  779. /**
  780. * @When user :user favorites element :path
  781. */
  782. public function userFavoritesElement($user, $path) {
  783. $this->response = $this->changeFavStateOfAnElement($user, $path, 1, 0, null);
  784. }
  785. /**
  786. * @When user :user unfavorites element :path
  787. */
  788. public function userUnfavoritesElement($user, $path) {
  789. $this->response = $this->changeFavStateOfAnElement($user, $path, 0, 0, null);
  790. }
  791. /*Set the elements of a proppatch, $folderDepth requires 1 to see elements without children*/
  792. public function changeFavStateOfAnElement($user, $path, $favOrUnfav, $folderDepth, $properties = null) {
  793. $fullUrl = substr($this->baseUrl, 0, -4);
  794. $settings = [
  795. 'baseUri' => $fullUrl,
  796. 'userName' => $user,
  797. ];
  798. if ($user === 'admin') {
  799. $settings['password'] = $this->adminUser[1];
  800. } else {
  801. $settings['password'] = $this->regularUser;
  802. }
  803. $settings['authType'] = SClient::AUTH_BASIC;
  804. $client = new SClient($settings);
  805. if (!$properties) {
  806. $properties = [
  807. '{http://owncloud.org/ns}favorite' => $favOrUnfav
  808. ];
  809. }
  810. $response = $client->proppatch($this->getDavFilesPath($user) . $path, $properties, $folderDepth);
  811. return $response;
  812. }
  813. /**
  814. * @Given user :user stores etag of element :path
  815. */
  816. public function userStoresEtagOfElement($user, $path) {
  817. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{DAV:}getetag']]);
  818. $this->asGetsPropertiesOfFolderWith($user, 'entry', $path, $propertiesTable);
  819. $pathETAG[$path] = $this->response['{DAV:}getetag'];
  820. $this->storedETAG[$user] = $pathETAG;
  821. }
  822. /**
  823. * @Then etag of element :path of user :user has not changed
  824. */
  825. public function checkIfETAGHasNotChanged($path, $user) {
  826. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{DAV:}getetag']]);
  827. $this->asGetsPropertiesOfFolderWith($user, 'entry', $path, $propertiesTable);
  828. Assert::assertEquals($this->response['{DAV:}getetag'], $this->storedETAG[$user][$path]);
  829. }
  830. /**
  831. * @Then etag of element :path of user :user has changed
  832. */
  833. public function checkIfETAGHasChanged($path, $user) {
  834. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{DAV:}getetag']]);
  835. $this->asGetsPropertiesOfFolderWith($user, 'entry', $path, $propertiesTable);
  836. Assert::assertNotEquals($this->response['{DAV:}getetag'], $this->storedETAG[$user][$path]);
  837. }
  838. /**
  839. * @When Connecting to dav endpoint
  840. */
  841. public function connectingToDavEndpoint() {
  842. try {
  843. $this->response = $this->makeDavRequest(null, 'PROPFIND', '', []);
  844. } catch (\GuzzleHttp\Exception\ClientException $e) {
  845. $this->response = $e->getResponse();
  846. }
  847. }
  848. /**
  849. * @When Requesting share note on dav endpoint
  850. */
  851. public function requestingShareNote() {
  852. $propfind = '<d:propfind xmlns:d="DAV:" xmlns:nc="http://nextcloud.org/ns"><d:prop><nc:note /></d:prop></d:propfind>';
  853. if (count($this->lastShareData->data->element) > 0) {
  854. $token = $this->lastShareData->data[0]->token;
  855. } else {
  856. $token = $this->lastShareData->data->token;
  857. }
  858. try {
  859. $this->response = $this->makeDavRequest('', 'PROPFIND', $token, [], $propfind);
  860. } catch (\GuzzleHttp\Exception\ClientException $e) {
  861. $this->response = $e->getResponse();
  862. }
  863. }
  864. /**
  865. * @Then there are no duplicate headers
  866. */
  867. public function thereAreNoDuplicateHeaders() {
  868. $headers = $this->response->getHeaders();
  869. foreach ($headers as $headerName => $headerValues) {
  870. // if a header has multiple values, they must be different
  871. if (count($headerValues) > 1 && count(array_unique($headerValues)) < count($headerValues)) {
  872. throw new \Exception('Duplicate header found: ' . $headerName);
  873. }
  874. }
  875. }
  876. /**
  877. * @Then /^user "([^"]*)" in folder "([^"]*)" should have favorited the following elements$/
  878. * @param string $user
  879. * @param string $folder
  880. * @param \Behat\Gherkin\Node\TableNode|null $expectedElements
  881. */
  882. public function checkFavoritedElements($user, $folder, $expectedElements) {
  883. $elementList = $this->reportFolder($user,
  884. $folder,
  885. '<oc:favorite/>',
  886. '<oc:favorite>1</oc:favorite>');
  887. if ($expectedElements instanceof \Behat\Gherkin\Node\TableNode) {
  888. $elementRows = $expectedElements->getRows();
  889. $elementsSimplified = $this->simplifyArray($elementRows);
  890. foreach ($elementsSimplified as $expectedElement) {
  891. $webdavPath = '/' . $this->getDavFilesPath($user) . $expectedElement;
  892. if (!array_key_exists($webdavPath, $elementList)) {
  893. Assert::fail("$webdavPath" . ' is not in report answer');
  894. }
  895. }
  896. }
  897. }
  898. /**
  899. * @When /^User "([^"]*)" deletes everything from folder "([^"]*)"$/
  900. * @param string $user
  901. * @param string $folder
  902. */
  903. public function userDeletesEverythingInFolder($user, $folder) {
  904. $elementList = $this->listFolder($user, $folder, 1);
  905. $elementListKeys = array_keys($elementList);
  906. array_shift($elementListKeys);
  907. $davPrefix = '/' . $this->getDavFilesPath($user);
  908. foreach ($elementListKeys as $element) {
  909. if (substr($element, 0, strlen($davPrefix)) == $davPrefix) {
  910. $element = substr($element, strlen($davPrefix));
  911. }
  912. $this->userDeletesFile($user, 'element', $element);
  913. }
  914. }
  915. /**
  916. * @param string $user
  917. * @param string $path
  918. * @return int
  919. */
  920. private function getFileIdForPath($user, $path) {
  921. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{http://owncloud.org/ns}fileid']]);
  922. $this->asGetsPropertiesOfFolderWith($user, 'file', $path, $propertiesTable);
  923. return (int)$this->response['{http://owncloud.org/ns}fileid'];
  924. }
  925. /**
  926. * @Given /^User "([^"]*)" stores id of file "([^"]*)"$/
  927. * @param string $user
  928. * @param string $path
  929. */
  930. public function userStoresFileIdForPath($user, $path) {
  931. $this->storedFileID = $this->getFileIdForPath($user, $path);
  932. }
  933. /**
  934. * @Given /^User "([^"]*)" checks id of file "([^"]*)"$/
  935. * @param string $user
  936. * @param string $path
  937. */
  938. public function userChecksFileIdForPath($user, $path) {
  939. $currentFileID = $this->getFileIdForPath($user, $path);
  940. Assert::assertEquals($currentFileID, $this->storedFileID);
  941. }
  942. /**
  943. * @Given /^user "([^"]*)" creates a file locally with "([^"]*)" x 5 MB chunks$/
  944. */
  945. public function userCreatesAFileLocallyWithChunks($arg1, $chunks) {
  946. $this->parts = [];
  947. for ($i = 1;$i <= (int)$chunks;$i++) {
  948. $randomletter = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 1);
  949. file_put_contents('/tmp/part-upload-' . $i, str_repeat($randomletter, 5 * 1024 * 1024));
  950. $this->parts[] = '/tmp/part-upload-' . $i;
  951. }
  952. }
  953. /**
  954. * @Given user :user creates the chunk :id with a size of :size MB
  955. */
  956. public function userCreatesAChunk($user, $id, $size) {
  957. $randomletter = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 1);
  958. file_put_contents('/tmp/part-upload-' . $id, str_repeat($randomletter, (int)$size * 1024 * 1024));
  959. $this->parts[] = '/tmp/part-upload-' . $id;
  960. }
  961. /**
  962. * @Then /^Downloaded content should be the created file$/
  963. */
  964. public function downloadedContentShouldBeTheCreatedFile() {
  965. $content = '';
  966. sort($this->parts);
  967. foreach ($this->parts as $part) {
  968. $content .= file_get_contents($part);
  969. }
  970. Assert::assertEquals($content, (string)$this->response->getBody());
  971. }
  972. /**
  973. * @Then /^the S3 multipart upload was successful with status "([^"]*)"$/
  974. */
  975. public function theSmultipartUploadWasSuccessful($status) {
  976. Assert::assertEquals((int)$status, $this->response->getStatusCode());
  977. }
  978. /**
  979. * @Then /^the upload should fail on object storage$/
  980. */
  981. public function theUploadShouldFailOnObjectStorage() {
  982. $descriptor = [
  983. 0 => ['pipe', 'r'],
  984. 1 => ['pipe', 'w'],
  985. 2 => ['pipe', 'w'],
  986. ];
  987. $process = proc_open('php occ config:system:get objectstore --no-ansi', $descriptor, $pipes, '../../');
  988. $lastCode = proc_close($process);
  989. if ($lastCode === 0) {
  990. $this->theHTTPStatusCodeShouldBe(500);
  991. }
  992. }
  993. /**
  994. * @return array
  995. * @throws Exception
  996. */
  997. private function convertResponseToDavSingleEntry(): array {
  998. $results = $this->convertResponseToDavEntries();
  999. if (count($results) > 1) {
  1000. throw new \Exception('result is empty or contain more than one (1) entry');
  1001. }
  1002. return array_shift($results);
  1003. }
  1004. /**
  1005. * @return array
  1006. */
  1007. private function convertResponseToDavEntries(): array {
  1008. $client = $this->getSabreClient($this->currentUser);
  1009. $parsedResponse = $client->parseMultiStatus((string)$this->response->getBody());
  1010. $results = [];
  1011. foreach ($parsedResponse as $href => $statusList) {
  1012. $results[$href] = $statusList[200] ?? [];
  1013. }
  1014. return $results;
  1015. }
  1016. }