WebDav.php 36 KB

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