WebDav.php 30 KB

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