WebDav.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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 Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Sergio Bertolin <sbertolin@solidgear.es>
  14. * @author Sergio Bertolín <sbertolin@solidgear.es>
  15. * @author Thomas Müller <thomas.mueller@tmit.eu>
  16. * @author Vincent Petry <vincent@nextcloud.com>
  17. *
  18. * @license GNU AGPL version 3 or any later version
  19. *
  20. * This program is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License as
  22. * published by the Free Software Foundation, either version 3 of the
  23. * License, or (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  32. *
  33. */
  34. use GuzzleHttp\Client as GClient;
  35. use GuzzleHttp\Message\ResponseInterface;
  36. use PHPUnit\Framework\Assert;
  37. use Sabre\DAV\Client as SClient;
  38. use Sabre\DAV\Xml\Property\ResourceType;
  39. require __DIR__ . '/../../vendor/autoload.php';
  40. trait WebDav {
  41. use Sharing;
  42. /** @var string */
  43. private $davPath = "remote.php/webdav";
  44. /** @var boolean */
  45. private $usingOldDavPath = true;
  46. /** @var ResponseInterface */
  47. private $response;
  48. /** @var array map with user as key and another map as value, which has path as key and etag as value */
  49. private $storedETAG = null;
  50. /** @var int */
  51. private $storedFileID = null;
  52. /**
  53. * @Given /^using dav path "([^"]*)"$/
  54. */
  55. public function usingDavPath($davPath) {
  56. $this->davPath = $davPath;
  57. }
  58. /**
  59. * @Given /^using old dav path$/
  60. */
  61. public function usingOldDavPath() {
  62. $this->davPath = "remote.php/webdav";
  63. $this->usingOldDavPath = true;
  64. }
  65. /**
  66. * @Given /^using new dav path$/
  67. */
  68. public function usingNewDavPath() {
  69. $this->davPath = "remote.php/dav";
  70. $this->usingOldDavPath = false;
  71. }
  72. public function getDavFilesPath($user) {
  73. if ($this->usingOldDavPath === true) {
  74. return $this->davPath;
  75. } else {
  76. return $this->davPath . '/files/' . $user;
  77. }
  78. }
  79. public function makeDavRequest($user, $method, $path, $headers, $body = null, $type = "files") {
  80. if ($type === "files") {
  81. $fullUrl = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . "$path";
  82. } elseif ($type === "uploads") {
  83. $fullUrl = substr($this->baseUrl, 0, -4) . $this->davPath . "$path";
  84. } else {
  85. $fullUrl = substr($this->baseUrl, 0, -4) . $this->davPath . '/' . $type . "$path";
  86. }
  87. $client = new GClient();
  88. $options = [
  89. 'headers' => $headers,
  90. 'body' => $body
  91. ];
  92. if ($user === 'admin') {
  93. $options['auth'] = $this->adminUser;
  94. } else {
  95. $options['auth'] = [$user, $this->regularUser];
  96. }
  97. return $client->request($method, $fullUrl, $options);
  98. }
  99. /**
  100. * @Given /^User "([^"]*)" moved (file|folder|entry) "([^"]*)" to "([^"]*)"$/
  101. * @param string $user
  102. * @param string $fileSource
  103. * @param string $fileDestination
  104. */
  105. public function userMovedFile($user, $entry, $fileSource, $fileDestination) {
  106. $fullUrl = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user);
  107. $headers['Destination'] = $fullUrl . $fileDestination;
  108. $this->response = $this->makeDavRequest($user, "MOVE", $fileSource, $headers);
  109. Assert::assertEquals(201, $this->response->getStatusCode());
  110. }
  111. /**
  112. * @When /^User "([^"]*)" moves (file|folder|entry) "([^"]*)" to "([^"]*)"$/
  113. * @param string $user
  114. * @param string $fileSource
  115. * @param string $fileDestination
  116. */
  117. public function userMovesFile($user, $entry, $fileSource, $fileDestination) {
  118. $fullUrl = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user);
  119. $headers['Destination'] = $fullUrl . $fileDestination;
  120. try {
  121. $this->response = $this->makeDavRequest($user, "MOVE", $fileSource, $headers);
  122. } catch (\GuzzleHttp\Exception\ClientException $e) {
  123. $this->response = $e->getResponse();
  124. }
  125. }
  126. /**
  127. * @When /^User "([^"]*)" copies file "([^"]*)" to "([^"]*)"$/
  128. * @param string $user
  129. * @param string $fileSource
  130. * @param string $fileDestination
  131. */
  132. public function userCopiesFileTo($user, $fileSource, $fileDestination) {
  133. $fullUrl = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user);
  134. $headers['Destination'] = $fullUrl . $fileDestination;
  135. try {
  136. $this->response = $this->makeDavRequest($user, 'COPY', $fileSource, $headers);
  137. } catch (\GuzzleHttp\Exception\ClientException $e) {
  138. // 4xx and 5xx responses cause an exception
  139. $this->response = $e->getResponse();
  140. }
  141. }
  142. /**
  143. * @When /^Downloading file "([^"]*)" with range "([^"]*)"$/
  144. * @param string $fileSource
  145. * @param string $range
  146. */
  147. public function downloadFileWithRange($fileSource, $range) {
  148. $headers['Range'] = $range;
  149. $this->response = $this->makeDavRequest($this->currentUser, "GET", $fileSource, $headers);
  150. }
  151. /**
  152. * @When /^Downloading last public shared file with range "([^"]*)"$/
  153. * @param string $range
  154. */
  155. public function downloadPublicFileWithRange($range) {
  156. $token = $this->lastShareData->data->token;
  157. $fullUrl = substr($this->baseUrl, 0, -4) . "public.php/webdav";
  158. $client = new GClient();
  159. $options = [];
  160. $options['auth'] = [$token, ""];
  161. $options['headers'] = [
  162. 'Range' => $range
  163. ];
  164. $this->response = $client->request("GET", $fullUrl, $options);
  165. }
  166. /**
  167. * @When /^Downloading last public shared file inside a folder "([^"]*)" with range "([^"]*)"$/
  168. * @param string $range
  169. */
  170. public function downloadPublicFileInsideAFolderWithRange($path, $range) {
  171. $token = $this->lastShareData->data->token;
  172. $fullUrl = substr($this->baseUrl, 0, -4) . "public.php/webdav" . "$path";
  173. $client = new GClient();
  174. $options = [
  175. 'headers' => [
  176. 'Range' => $range
  177. ]
  178. ];
  179. $options['auth'] = [$token, ""];
  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 /^Downloaded content when downloading file "([^"]*)" with range "([^"]*)" should be "([^"]*)"$/
  203. * @param string $fileSource
  204. * @param string $range
  205. * @param string $content
  206. */
  207. public function downloadedContentWhenDownloadindShouldBe($fileSource, $range, $content) {
  208. $this->downloadFileWithRange($fileSource, $range);
  209. $this->downloadedContentShouldBe($content);
  210. }
  211. /**
  212. * @When Downloading file :fileName
  213. * @param string $fileName
  214. */
  215. public function downloadingFile($fileName) {
  216. try {
  217. $this->response = $this->makeDavRequest($this->currentUser, 'GET', $fileName, []);
  218. } catch (\GuzzleHttp\Exception\ClientException $e) {
  219. $this->response = $e->getResponse();
  220. }
  221. }
  222. /**
  223. * @Then Downloaded content should start with :start
  224. * @param int $start
  225. * @throws \Exception
  226. */
  227. public function downloadedContentShouldStartWith($start) {
  228. if (strpos($this->response->getBody()->getContents(), $start) !== 0) {
  229. throw new \Exception(
  230. sprintf(
  231. "Expected '%s', got '%s'",
  232. $start,
  233. $this->response->getBody()->getContents()
  234. )
  235. );
  236. }
  237. }
  238. /**
  239. * @Then /^as "([^"]*)" gets properties of (file|folder|entry) "([^"]*)" with$/
  240. * @param string $user
  241. * @param string $elementType
  242. * @param string $path
  243. * @param \Behat\Gherkin\Node\TableNode|null $propertiesTable
  244. */
  245. public function asGetsPropertiesOfFolderWith($user, $elementType, $path, $propertiesTable) {
  246. $properties = null;
  247. if ($propertiesTable instanceof \Behat\Gherkin\Node\TableNode) {
  248. foreach ($propertiesTable->getRows() as $row) {
  249. $properties[] = $row[0];
  250. }
  251. }
  252. $this->response = $this->listFolder($user, $path, 0, $properties);
  253. }
  254. /**
  255. * @Then /^as "([^"]*)" the (file|folder|entry) "([^"]*)" does not exist$/
  256. * @param string $user
  257. * @param string $entry
  258. * @param string $path
  259. * @param \Behat\Gherkin\Node\TableNode|null $propertiesTable
  260. */
  261. public function asTheFileOrFolderDoesNotExist($user, $entry, $path) {
  262. $client = $this->getSabreClient($user);
  263. $response = $client->request('HEAD', $this->makeSabrePath($user, $path));
  264. if ($response['statusCode'] !== 404) {
  265. throw new \Exception($entry . ' "' . $path . '" expected to not exist (status code ' . $response['statusCode'] . ', expected 404)');
  266. }
  267. return $response;
  268. }
  269. /**
  270. * @Then /^as "([^"]*)" the (file|folder|entry) "([^"]*)" exists$/
  271. * @param string $user
  272. * @param string $entry
  273. * @param string $path
  274. */
  275. public function asTheFileOrFolderExists($user, $entry, $path) {
  276. $this->response = $this->listFolder($user, $path, 0);
  277. }
  278. /**
  279. * @Then the single response should contain a property :key with value :value
  280. * @param string $key
  281. * @param string $expectedValue
  282. * @throws \Exception
  283. */
  284. public function theSingleResponseShouldContainAPropertyWithValue($key, $expectedValue) {
  285. $keys = $this->response;
  286. if (!array_key_exists($key, $keys)) {
  287. throw new \Exception("Cannot find property \"$key\" with \"$expectedValue\"");
  288. }
  289. $value = $keys[$key];
  290. if ($value instanceof ResourceType) {
  291. $value = $value->getValue();
  292. if (empty($value)) {
  293. $value = '';
  294. } else {
  295. $value = $value[0];
  296. }
  297. }
  298. if ($value != $expectedValue) {
  299. throw new \Exception("Property \"$key\" found with value \"$value\", expected \"$expectedValue\"");
  300. }
  301. }
  302. /**
  303. * @Then the response should contain a share-types property with
  304. */
  305. public function theResponseShouldContainAShareTypesPropertyWith($table) {
  306. $keys = $this->response;
  307. if (!array_key_exists('{http://owncloud.org/ns}share-types', $keys)) {
  308. throw new \Exception("Cannot find property \"{http://owncloud.org/ns}share-types\"");
  309. }
  310. $foundTypes = [];
  311. $data = $keys['{http://owncloud.org/ns}share-types'];
  312. foreach ($data as $item) {
  313. if ($item['name'] !== '{http://owncloud.org/ns}share-type') {
  314. throw new \Exception('Invalid property found: "' . $item['name'] . '"');
  315. }
  316. $foundTypes[] = $item['value'];
  317. }
  318. foreach ($table->getRows() as $row) {
  319. $key = array_search($row[0], $foundTypes);
  320. if ($key === false) {
  321. throw new \Exception('Expected type ' . $row[0] . ' not found');
  322. }
  323. unset($foundTypes[$key]);
  324. }
  325. if ($foundTypes !== []) {
  326. throw new \Exception('Found more share types then specified: ' . $foundTypes);
  327. }
  328. }
  329. /**
  330. * @Then the response should contain an empty property :property
  331. * @param string $property
  332. * @throws \Exception
  333. */
  334. public function theResponseShouldContainAnEmptyProperty($property) {
  335. $properties = $this->response;
  336. if (!array_key_exists($property, $properties)) {
  337. throw new \Exception("Cannot find property \"$property\"");
  338. }
  339. if ($properties[$property] !== null) {
  340. throw new \Exception("Property \"$property\" is not empty");
  341. }
  342. }
  343. /*Returns the elements of a propfind, $folderDepth requires 1 to see elements without children*/
  344. public function listFolder($user, $path, $folderDepth, $properties = null) {
  345. $client = $this->getSabreClient($user);
  346. if (!$properties) {
  347. $properties = [
  348. '{DAV:}getetag'
  349. ];
  350. }
  351. $response = $client->propfind($this->makeSabrePath($user, $path), $properties, $folderDepth);
  352. return $response;
  353. }
  354. /* Returns the elements of a report command
  355. * @param string $user
  356. * @param string $path
  357. * @param string $properties properties which needs to be included in the report
  358. * @param string $filterRules filter-rules to choose what needs to appear in the report
  359. */
  360. public function propfindFile($user, $path, $properties = '') {
  361. $client = $this->getSabreClient($user);
  362. $body = '<?xml version="1.0" encoding="utf-8" ?>
  363. <d:propfind xmlns:d="DAV:"
  364. xmlns:oc="http://owncloud.org/ns"
  365. xmlns:nc="http://nextcloud.org/ns"
  366. xmlns:ocs="http://open-collaboration-services.org/ns">
  367. <d:prop>
  368. ' . $properties . '
  369. </d:prop>
  370. </d:propfind>';
  371. $response = $client->request('PROPFIND', $this->makeSabrePath($user, $path), $body);
  372. $parsedResponse = $client->parseMultistatus($response['body']);
  373. return $parsedResponse;
  374. }
  375. /* Returns the elements of a report command
  376. * @param string $user
  377. * @param string $path
  378. * @param string $properties properties which needs to be included in the report
  379. * @param string $filterRules filter-rules to choose what needs to appear in the report
  380. */
  381. public function reportFolder($user, $path, $properties, $filterRules) {
  382. $client = $this->getSabreClient($user);
  383. $body = '<?xml version="1.0" encoding="utf-8" ?>
  384. <oc:filter-files xmlns:a="DAV:" xmlns:oc="http://owncloud.org/ns" >
  385. <a:prop>
  386. ' . $properties . '
  387. </a:prop>
  388. <oc:filter-rules>
  389. ' . $filterRules . '
  390. </oc:filter-rules>
  391. </oc:filter-files>';
  392. $response = $client->request('REPORT', $this->makeSabrePath($user, $path), $body);
  393. $parsedResponse = $client->parseMultistatus($response['body']);
  394. return $parsedResponse;
  395. }
  396. public function makeSabrePath($user, $path, $type = 'files') {
  397. if ($type === 'files') {
  398. return $this->encodePath($this->getDavFilesPath($user) . $path);
  399. } else {
  400. return $this->encodePath($this->davPath . '/' . $type . '/' . $user . '/' . $path);
  401. }
  402. }
  403. public function getSabreClient($user) {
  404. $fullUrl = substr($this->baseUrl, 0, -4);
  405. $settings = [
  406. 'baseUri' => $fullUrl,
  407. 'userName' => $user,
  408. ];
  409. if ($user === 'admin') {
  410. $settings['password'] = $this->adminUser[1];
  411. } else {
  412. $settings['password'] = $this->regularUser;
  413. }
  414. $settings['authType'] = SClient::AUTH_BASIC;
  415. return new SClient($settings);
  416. }
  417. /**
  418. * @Then /^user "([^"]*)" should see following elements$/
  419. * @param string $user
  420. * @param \Behat\Gherkin\Node\TableNode|null $expectedElements
  421. */
  422. public function checkElementList($user, $expectedElements) {
  423. $elementList = $this->listFolder($user, '/', 3);
  424. if ($expectedElements instanceof \Behat\Gherkin\Node\TableNode) {
  425. $elementRows = $expectedElements->getRows();
  426. $elementsSimplified = $this->simplifyArray($elementRows);
  427. foreach ($elementsSimplified as $expectedElement) {
  428. $webdavPath = "/" . $this->getDavFilesPath($user) . $expectedElement;
  429. if (!array_key_exists($webdavPath, $elementList)) {
  430. Assert::fail("$webdavPath" . " is not in propfind answer");
  431. }
  432. }
  433. }
  434. }
  435. /**
  436. * @When User :user uploads file :source to :destination
  437. * @param string $user
  438. * @param string $source
  439. * @param string $destination
  440. */
  441. public function userUploadsAFileTo($user, $source, $destination) {
  442. $file = \GuzzleHttp\Psr7\Utils::streamFor(fopen($source, 'r'));
  443. try {
  444. $this->response = $this->makeDavRequest($user, "PUT", $destination, [], $file);
  445. } catch (\GuzzleHttp\Exception\ServerException $e) {
  446. // 5xx responses cause a server exception
  447. $this->response = $e->getResponse();
  448. } catch (\GuzzleHttp\Exception\ClientException $e) {
  449. // 4xx responses cause a client exception
  450. $this->response = $e->getResponse();
  451. }
  452. }
  453. /**
  454. * @When User :user adds a file of :bytes bytes to :destination
  455. * @param string $user
  456. * @param string $bytes
  457. * @param string $destination
  458. */
  459. public function userAddsAFileTo($user, $bytes, $destination) {
  460. $filename = "filespecificSize.txt";
  461. $this->createFileSpecificSize($filename, $bytes);
  462. Assert::assertEquals(1, file_exists("work/$filename"));
  463. $this->userUploadsAFileTo($user, "work/$filename", $destination);
  464. $this->removeFile("work/", $filename);
  465. $expectedElements = new \Behat\Gherkin\Node\TableNode([["$destination"]]);
  466. $this->checkElementList($user, $expectedElements);
  467. }
  468. /**
  469. * @When User :user uploads file with content :content to :destination
  470. */
  471. public function userUploadsAFileWithContentTo($user, $content, $destination) {
  472. $file = \GuzzleHttp\Psr7\Utils::streamFor($content);
  473. try {
  474. $this->response = $this->makeDavRequest($user, "PUT", $destination, [], $file);
  475. } catch (\GuzzleHttp\Exception\ServerException $e) {
  476. // 5xx responses cause a server exception
  477. $this->response = $e->getResponse();
  478. } catch (\GuzzleHttp\Exception\ClientException $e) {
  479. // 4xx responses cause a client exception
  480. $this->response = $e->getResponse();
  481. }
  482. }
  483. /**
  484. * @When /^User "([^"]*)" deletes (file|folder) "([^"]*)"$/
  485. * @param string $user
  486. * @param string $type
  487. * @param string $file
  488. */
  489. public function userDeletesFile($user, $type, $file) {
  490. try {
  491. $this->response = $this->makeDavRequest($user, 'DELETE', $file, []);
  492. } catch (\GuzzleHttp\Exception\ServerException $e) {
  493. // 5xx responses cause a server exception
  494. $this->response = $e->getResponse();
  495. } catch (\GuzzleHttp\Exception\ClientException $e) {
  496. // 4xx responses cause a client exception
  497. $this->response = $e->getResponse();
  498. }
  499. }
  500. /**
  501. * @Given User :user created a folder :destination
  502. * @param string $user
  503. * @param string $destination
  504. */
  505. public function userCreatedAFolder($user, $destination) {
  506. try {
  507. $destination = '/' . ltrim($destination, '/');
  508. $this->response = $this->makeDavRequest($user, "MKCOL", $destination, []);
  509. } catch (\GuzzleHttp\Exception\ServerException $e) {
  510. // 5xx responses cause a server exception
  511. $this->response = $e->getResponse();
  512. } catch (\GuzzleHttp\Exception\ClientException $e) {
  513. // 4xx responses cause a client exception
  514. $this->response = $e->getResponse();
  515. }
  516. }
  517. /**
  518. * @Given user :user uploads chunk file :num of :total with :data to :destination
  519. * @param string $user
  520. * @param int $num
  521. * @param int $total
  522. * @param string $data
  523. * @param string $destination
  524. */
  525. public function userUploadsChunkFileOfWithToWithChecksum($user, $num, $total, $data, $destination) {
  526. $num -= 1;
  527. $data = \GuzzleHttp\Psr7\Utils::streamFor($data);
  528. $file = $destination . '-chunking-42-' . $total . '-' . $num;
  529. $this->makeDavRequest($user, 'PUT', $file, ['OC-Chunked' => '1'], $data, "uploads");
  530. }
  531. /**
  532. * @Given user :user uploads bulked files :name1 with :content1 and :name2 with :content2 and :name3 with :content3
  533. * @param string $user
  534. * @param string $name1
  535. * @param string $content1
  536. * @param string $name2
  537. * @param string $content2
  538. * @param string $name3
  539. * @param string $content3
  540. */
  541. public function userUploadsBulkedFiles($user, $name1, $content1, $name2, $content2, $name3, $content3) {
  542. $boundary = "boundary_azertyuiop";
  543. $body = "";
  544. $body .= '--'.$boundary."\r\n";
  545. $body .= "X-File-Path: ".$name1."\r\n";
  546. $body .= "X-File-MD5: f6a6263167c92de8644ac998b3c4e4d1\r\n";
  547. $body .= "X-OC-Mtime: 1111111111\r\n";
  548. $body .= "Content-Length: ".strlen($content1)."\r\n";
  549. $body .= "\r\n";
  550. $body .= $content1."\r\n";
  551. $body .= '--'.$boundary."\r\n";
  552. $body .= "X-File-Path: ".$name2."\r\n";
  553. $body .= "X-File-MD5: 87c7d4068be07d390a1fffd21bf1e944\r\n";
  554. $body .= "X-OC-Mtime: 2222222222\r\n";
  555. $body .= "Content-Length: ".strlen($content2)."\r\n";
  556. $body .= "\r\n";
  557. $body .= $content2."\r\n";
  558. $body .= '--'.$boundary."\r\n";
  559. $body .= "X-File-Path: ".$name3."\r\n";
  560. $body .= "X-File-MD5: e86a1cf0678099986a901c79086f5617\r\n";
  561. $body .= "X-File-Mtime: 3333333333\r\n";
  562. $body .= "Content-Length: ".strlen($content3)."\r\n";
  563. $body .= "\r\n";
  564. $body .= $content3."\r\n";
  565. $body .= '--'.$boundary."--\r\n";
  566. $stream = fopen('php://temp', 'r+');
  567. fwrite($stream, $body);
  568. rewind($stream);
  569. $client = new GClient();
  570. $options = [
  571. 'auth' => [$user, $this->regularUser],
  572. 'headers' => [
  573. 'Content-Type' => 'multipart/related; boundary='.$boundary,
  574. 'Content-Length' => (string)strlen($body),
  575. ],
  576. 'body' => $body
  577. ];
  578. return $client->request("POST", substr($this->baseUrl, 0, -4) . "remote.php/dav/bulk", $options);
  579. }
  580. /**
  581. * @Given user :user creates a new chunking upload with id :id
  582. */
  583. public function userCreatesANewChunkingUploadWithId($user, $id) {
  584. $destination = '/uploads/' . $user . '/' . $id;
  585. $this->makeDavRequest($user, 'MKCOL', $destination, [], null, "uploads");
  586. }
  587. /**
  588. * @Given user :user uploads new chunk file :num with :data to id :id
  589. */
  590. public function userUploadsNewChunkFileOfWithToId($user, $num, $data, $id) {
  591. $data = \GuzzleHttp\Psr7\Utils::streamFor($data);
  592. $destination = '/uploads/' . $user . '/' . $id . '/' . $num;
  593. $this->makeDavRequest($user, 'PUT', $destination, [], $data, "uploads");
  594. }
  595. /**
  596. * @Given user :user moves new chunk file with id :id to :dest
  597. */
  598. public function userMovesNewChunkFileWithIdToMychunkedfile($user, $id, $dest) {
  599. $source = '/uploads/' . $user . '/' . $id . '/.file';
  600. $destination = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . $dest;
  601. $this->makeDavRequest($user, 'MOVE', $source, [
  602. 'Destination' => $destination
  603. ], null, "uploads");
  604. }
  605. /**
  606. * @Then user :user moves new chunk file with id :id to :dest with size :size
  607. */
  608. public function userMovesNewChunkFileWithIdToMychunkedfileWithSize($user, $id, $dest, $size) {
  609. $source = '/uploads/' . $user . '/' . $id . '/.file';
  610. $destination = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user) . $dest;
  611. try {
  612. $this->response = $this->makeDavRequest($user, 'MOVE', $source, [
  613. 'Destination' => $destination,
  614. 'OC-Total-Length' => $size
  615. ], null, "uploads");
  616. } catch (\GuzzleHttp\Exception\BadResponseException $ex) {
  617. $this->response = $ex->getResponse();
  618. }
  619. }
  620. /**
  621. * @Given /^Downloading file "([^"]*)" as "([^"]*)"$/
  622. */
  623. public function downloadingFileAs($fileName, $user) {
  624. try {
  625. $this->response = $this->makeDavRequest($user, 'GET', $fileName, []);
  626. } catch (\GuzzleHttp\Exception\ServerException $e) {
  627. // 5xx responses cause a server exception
  628. $this->response = $e->getResponse();
  629. } catch (\GuzzleHttp\Exception\ClientException $e) {
  630. // 4xx responses cause a client exception
  631. $this->response = $e->getResponse();
  632. }
  633. }
  634. /**
  635. * URL encodes the given path but keeps the slashes
  636. *
  637. * @param string $path to encode
  638. * @return string encoded path
  639. */
  640. private function encodePath($path) {
  641. // slashes need to stay
  642. return str_replace('%2F', '/', rawurlencode($path));
  643. }
  644. /**
  645. * @When user :user favorites element :path
  646. */
  647. public function userFavoritesElement($user, $path) {
  648. $this->response = $this->changeFavStateOfAnElement($user, $path, 1, 0, null);
  649. }
  650. /**
  651. * @When user :user unfavorites element :path
  652. */
  653. public function userUnfavoritesElement($user, $path) {
  654. $this->response = $this->changeFavStateOfAnElement($user, $path, 0, 0, null);
  655. }
  656. /*Set the elements of a proppatch, $folderDepth requires 1 to see elements without children*/
  657. public function changeFavStateOfAnElement($user, $path, $favOrUnfav, $folderDepth, $properties = null) {
  658. $fullUrl = substr($this->baseUrl, 0, -4);
  659. $settings = [
  660. 'baseUri' => $fullUrl,
  661. 'userName' => $user,
  662. ];
  663. if ($user === 'admin') {
  664. $settings['password'] = $this->adminUser[1];
  665. } else {
  666. $settings['password'] = $this->regularUser;
  667. }
  668. $settings['authType'] = SClient::AUTH_BASIC;
  669. $client = new SClient($settings);
  670. if (!$properties) {
  671. $properties = [
  672. '{http://owncloud.org/ns}favorite' => $favOrUnfav
  673. ];
  674. }
  675. $response = $client->proppatch($this->getDavFilesPath($user) . $path, $properties, $folderDepth);
  676. return $response;
  677. }
  678. /**
  679. * @Given user :user stores etag of element :path
  680. */
  681. public function userStoresEtagOfElement($user, $path) {
  682. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{DAV:}getetag']]);
  683. $this->asGetsPropertiesOfFolderWith($user, 'entry', $path, $propertiesTable);
  684. $pathETAG[$path] = $this->response['{DAV:}getetag'];
  685. $this->storedETAG[$user] = $pathETAG;
  686. }
  687. /**
  688. * @Then etag of element :path of user :user has not changed
  689. */
  690. public function checkIfETAGHasNotChanged($path, $user) {
  691. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{DAV:}getetag']]);
  692. $this->asGetsPropertiesOfFolderWith($user, 'entry', $path, $propertiesTable);
  693. Assert::assertEquals($this->response['{DAV:}getetag'], $this->storedETAG[$user][$path]);
  694. }
  695. /**
  696. * @Then etag of element :path of user :user has changed
  697. */
  698. public function checkIfETAGHasChanged($path, $user) {
  699. $propertiesTable = new \Behat\Gherkin\Node\TableNode([['{DAV:}getetag']]);
  700. $this->asGetsPropertiesOfFolderWith($user, 'entry', $path, $propertiesTable);
  701. Assert::assertNotEquals($this->response['{DAV:}getetag'], $this->storedETAG[$user][$path]);
  702. }
  703. /**
  704. * @When Connecting to dav endpoint
  705. */
  706. public function connectingToDavEndpoint() {
  707. try {
  708. $this->response = $this->makeDavRequest(null, 'PROPFIND', '', []);
  709. } catch (\GuzzleHttp\Exception\ClientException $e) {
  710. $this->response = $e->getResponse();
  711. }
  712. }
  713. /**
  714. * @Then there are no duplicate headers
  715. */
  716. public function thereAreNoDuplicateHeaders() {
  717. $headers = $this->response->getHeaders();
  718. foreach ($headers as $headerName => $headerValues) {
  719. // if a header has multiple values, they must be different
  720. if (count($headerValues) > 1 && count(array_unique($headerValues)) < count($headerValues)) {
  721. throw new \Exception('Duplicate header found: ' . $headerName);
  722. }
  723. }
  724. }
  725. /**
  726. * @Then /^user "([^"]*)" in folder "([^"]*)" should have favorited the following elements$/
  727. * @param string $user
  728. * @param string $folder
  729. * @param \Behat\Gherkin\Node\TableNode|null $expectedElements
  730. */
  731. public function checkFavoritedElements($user, $folder, $expectedElements) {
  732. $elementList = $this->reportFolder($user,
  733. $folder,
  734. '<oc:favorite/>',
  735. '<oc:favorite>1</oc:favorite>');
  736. if ($expectedElements instanceof \Behat\Gherkin\Node\TableNode) {
  737. $elementRows = $expectedElements->getRows();
  738. $elementsSimplified = $this->simplifyArray($elementRows);
  739. foreach ($elementsSimplified as $expectedElement) {
  740. $webdavPath = "/" . $this->getDavFilesPath($user) . $expectedElement;
  741. if (!array_key_exists($webdavPath, $elementList)) {
  742. Assert::fail("$webdavPath" . " is not in report answer");
  743. }
  744. }
  745. }
  746. }
  747. /**
  748. * @When /^User "([^"]*)" deletes everything from folder "([^"]*)"$/
  749. * @param string $user
  750. * @param string $folder
  751. */
  752. public function userDeletesEverythingInFolder($user, $folder) {
  753. $elementList = $this->listFolder($user, $folder, 1);
  754. $elementListKeys = array_keys($elementList);
  755. array_shift($elementListKeys);
  756. $davPrefix = "/" . $this->getDavFilesPath($user);
  757. foreach ($elementListKeys as $element) {
  758. if (substr($element, 0, strlen($davPrefix)) == $davPrefix) {
  759. $element = substr($element, strlen($davPrefix));
  760. }
  761. $this->userDeletesFile($user, "element", $element);
  762. }
  763. }
  764. /**
  765. * @param string $user
  766. * @param string $path
  767. * @return int
  768. */
  769. private function getFileIdForPath($user, $path) {
  770. $propertiesTable = new \Behat\Gherkin\Node\TableNode([["{http://owncloud.org/ns}fileid"]]);
  771. $this->asGetsPropertiesOfFolderWith($user, 'file', $path, $propertiesTable);
  772. return (int)$this->response['{http://owncloud.org/ns}fileid'];
  773. }
  774. /**
  775. * @Given /^User "([^"]*)" stores id of file "([^"]*)"$/
  776. * @param string $user
  777. * @param string $path
  778. */
  779. public function userStoresFileIdForPath($user, $path) {
  780. $this->storedFileID = $this->getFileIdForPath($user, $path);
  781. }
  782. /**
  783. * @Given /^User "([^"]*)" checks id of file "([^"]*)"$/
  784. * @param string $user
  785. * @param string $path
  786. */
  787. public function userChecksFileIdForPath($user, $path) {
  788. $currentFileID = $this->getFileIdForPath($user, $path);
  789. Assert::assertEquals($currentFileID, $this->storedFileID);
  790. }
  791. }