Sharing.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. use Behat\Gherkin\Node\TableNode;
  8. use GuzzleHttp\Client;
  9. use PHPUnit\Framework\Assert;
  10. use Psr\Http\Message\ResponseInterface;
  11. require __DIR__ . '/../../vendor/autoload.php';
  12. trait Sharing {
  13. use Provisioning;
  14. /** @var int */
  15. private $sharingApiVersion = 1;
  16. /** @var SimpleXMLElement */
  17. private $lastShareData = null;
  18. /** @var SimpleXMLElement[] */
  19. private $storedShareData = [];
  20. /** @var int */
  21. private $savedShareId = null;
  22. /** @var ResponseInterface */
  23. private $response;
  24. /**
  25. * @Given /^as "([^"]*)" creating a share with$/
  26. * @param string $user
  27. * @param TableNode|null $body
  28. */
  29. public function asCreatingAShareWith($user, $body) {
  30. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares";
  31. $client = new Client();
  32. $options = [
  33. 'headers' => [
  34. 'OCS-APIREQUEST' => 'true',
  35. ],
  36. ];
  37. if ($user === 'admin') {
  38. $options['auth'] = $this->adminUser;
  39. } else {
  40. $options['auth'] = [$user, $this->regularUser];
  41. }
  42. if ($body instanceof TableNode) {
  43. $fd = $body->getRowsHash();
  44. if (array_key_exists('expireDate', $fd)) {
  45. $dateModification = $fd['expireDate'];
  46. $fd['expireDate'] = date('Y-m-d', strtotime($dateModification));
  47. }
  48. $options['form_params'] = $fd;
  49. }
  50. try {
  51. $this->response = $client->request("POST", $fullUrl, $options);
  52. } catch (\GuzzleHttp\Exception\ClientException $ex) {
  53. $this->response = $ex->getResponse();
  54. }
  55. $this->lastShareData = simplexml_load_string($this->response->getBody());
  56. }
  57. /**
  58. * @When /^save the last share data as "([^"]*)"$/
  59. */
  60. public function saveLastShareData($name) {
  61. $this->storedShareData[$name] = $this->lastShareData;
  62. }
  63. /**
  64. * @When /^restore the last share data from "([^"]*)"$/
  65. */
  66. public function restoreLastShareData($name) {
  67. $this->lastShareData = $this->storedShareData[$name];
  68. }
  69. /**
  70. * @When /^creating a share with$/
  71. * @param TableNode|null $body
  72. */
  73. public function creatingShare($body) {
  74. $this->asCreatingAShareWith($this->currentUser, $body);
  75. }
  76. /**
  77. * @When /^accepting last share$/
  78. */
  79. public function acceptingLastShare() {
  80. $share_id = $this->lastShareData->data[0]->id;
  81. $url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/pending/$share_id";
  82. $this->sendingToWith("POST", $url, null);
  83. $this->theHTTPStatusCodeShouldBe('200');
  84. }
  85. /**
  86. * @When /^user "([^"]*)" accepts last share$/
  87. *
  88. * @param string $user
  89. */
  90. public function userAcceptsLastShare(string $user) {
  91. // "As userXXX" and "user userXXX accepts last share" steps are not
  92. // expected to be used in the same scenario, but restore the user just
  93. // in case.
  94. $previousUser = $this->currentUser;
  95. $this->currentUser = $user;
  96. $share_id = $this->lastShareData->data[0]->id;
  97. $url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/pending/$share_id";
  98. $this->sendingToWith("POST", $url, null);
  99. $this->currentUser = $previousUser;
  100. $this->theHTTPStatusCodeShouldBe('200');
  101. }
  102. /**
  103. * @Then /^last link share can be downloaded$/
  104. */
  105. public function lastLinkShareCanBeDownloaded() {
  106. if (count($this->lastShareData->data->element) > 0) {
  107. $url = $this->lastShareData->data[0]->url;
  108. } else {
  109. $url = $this->lastShareData->data->url;
  110. }
  111. $fullUrl = $url . "/download";
  112. $this->checkDownload($fullUrl, null, 'text/plain');
  113. }
  114. /**
  115. * @Then /^last share can be downloaded$/
  116. */
  117. public function lastShareCanBeDownloaded() {
  118. if (count($this->lastShareData->data->element) > 0) {
  119. $token = $this->lastShareData->data[0]->token;
  120. } else {
  121. $token = $this->lastShareData->data->token;
  122. }
  123. $fullUrl = substr($this->baseUrl, 0, -4) . "index.php/s/" . $token . "/download";
  124. $this->checkDownload($fullUrl, null, 'text/plain');
  125. }
  126. /**
  127. * @Then /^last share with password "([^"]*)" can be downloaded$/
  128. */
  129. public function lastShareWithPasswordCanBeDownloaded($password) {
  130. if (count($this->lastShareData->data->element) > 0) {
  131. $token = $this->lastShareData->data[0]->token;
  132. } else {
  133. $token = $this->lastShareData->data->token;
  134. }
  135. $fullUrl = substr($this->baseUrl, 0, -4) . "public.php/dav/files/$token/";
  136. $this->checkDownload($fullUrl, ['', $password], 'text/plain');
  137. }
  138. private function checkDownload($url, $auth = null, $mimeType = null) {
  139. if ($auth !== null) {
  140. $options['auth'] = $auth;
  141. }
  142. $options['stream'] = true;
  143. $client = new Client();
  144. $this->response = $client->get($url, $options);
  145. Assert::assertEquals(200, $this->response->getStatusCode());
  146. $buf = '';
  147. $body = $this->response->getBody();
  148. while (!$body->eof()) {
  149. // read everything
  150. $buf .= $body->read(8192);
  151. }
  152. $body->close();
  153. if ($mimeType !== null) {
  154. $finfo = new finfo;
  155. Assert::assertEquals($mimeType, $finfo->buffer($buf, FILEINFO_MIME_TYPE));
  156. }
  157. }
  158. /**
  159. * @When /^Adding expiration date to last share$/
  160. */
  161. public function addingExpirationDate() {
  162. $share_id = (string) $this->lastShareData->data[0]->id;
  163. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  164. $client = new Client();
  165. $options = [];
  166. if ($this->currentUser === 'admin') {
  167. $options['auth'] = $this->adminUser;
  168. } else {
  169. $options['auth'] = [$this->currentUser, $this->regularUser];
  170. }
  171. $date = date('Y-m-d', strtotime("+3 days"));
  172. $options['form_params'] = ['expireDate' => $date];
  173. $this->response = $this->response = $client->request("PUT", $fullUrl, $options);
  174. Assert::assertEquals(200, $this->response->getStatusCode());
  175. }
  176. /**
  177. * @When /^Updating last share with$/
  178. * @param TableNode|null $body
  179. */
  180. public function updatingLastShare($body) {
  181. $share_id = (string) $this->lastShareData->data[0]->id;
  182. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  183. $client = new Client();
  184. $options = [
  185. 'headers' => [
  186. 'OCS-APIREQUEST' => 'true',
  187. ],
  188. ];
  189. if ($this->currentUser === 'admin') {
  190. $options['auth'] = $this->adminUser;
  191. } else {
  192. $options['auth'] = [$this->currentUser, $this->regularUser];
  193. }
  194. if ($body instanceof TableNode) {
  195. $fd = $body->getRowsHash();
  196. if (array_key_exists('expireDate', $fd)) {
  197. $dateModification = $fd['expireDate'];
  198. $fd['expireDate'] = date('Y-m-d', strtotime($dateModification));
  199. }
  200. $options['form_params'] = $fd;
  201. }
  202. try {
  203. $this->response = $client->request("PUT", $fullUrl, $options);
  204. } catch (\GuzzleHttp\Exception\ClientException $ex) {
  205. $this->response = $ex->getResponse();
  206. }
  207. }
  208. public function createShare($user,
  209. $path = null,
  210. $shareType = null,
  211. $shareWith = null,
  212. $publicUpload = null,
  213. $password = null,
  214. $permissions = null,
  215. $viewOnly = false) {
  216. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares";
  217. $client = new Client();
  218. $options = [
  219. 'headers' => [
  220. 'OCS-APIREQUEST' => 'true',
  221. ],
  222. ];
  223. if ($user === 'admin') {
  224. $options['auth'] = $this->adminUser;
  225. } else {
  226. $options['auth'] = [$user, $this->regularUser];
  227. }
  228. $body = [];
  229. if (!is_null($path)) {
  230. $body['path'] = $path;
  231. }
  232. if (!is_null($shareType)) {
  233. $body['shareType'] = $shareType;
  234. }
  235. if (!is_null($shareWith)) {
  236. $body['shareWith'] = $shareWith;
  237. }
  238. if (!is_null($publicUpload)) {
  239. $body['publicUpload'] = $publicUpload;
  240. }
  241. if (!is_null($password)) {
  242. $body['password'] = $password;
  243. }
  244. if (!is_null($permissions)) {
  245. $body['permissions'] = $permissions;
  246. }
  247. if ($viewOnly === true) {
  248. $body['attributes'] = json_encode([['scope' => 'permissions', 'key' => 'download', 'enabled' => false]]);
  249. }
  250. $options['form_params'] = $body;
  251. try {
  252. $this->response = $client->request("POST", $fullUrl, $options);
  253. $this->lastShareData = simplexml_load_string($this->response->getBody());
  254. } catch (\GuzzleHttp\Exception\ClientException $ex) {
  255. $this->response = $ex->getResponse();
  256. throw new \Exception($this->response->getBody());
  257. }
  258. }
  259. public function isFieldInResponse($field, $contentExpected) {
  260. $data = simplexml_load_string($this->response->getBody())->data[0];
  261. if ((string)$field == 'expiration') {
  262. $contentExpected = date('Y-m-d', strtotime($contentExpected)) . " 00:00:00";
  263. }
  264. if (count($data->element) > 0) {
  265. foreach ($data as $element) {
  266. if ($contentExpected == "A_TOKEN") {
  267. return (strlen((string)$element->$field) == 15);
  268. } elseif ($contentExpected == "A_NUMBER") {
  269. return is_numeric((string)$element->$field);
  270. } elseif ($contentExpected == "AN_URL") {
  271. return $this->isExpectedUrl((string)$element->$field, "index.php/s/");
  272. } elseif ((string)$element->$field == $contentExpected) {
  273. return true;
  274. } else {
  275. print($element->$field);
  276. }
  277. }
  278. return false;
  279. } else {
  280. if ($contentExpected == "A_TOKEN") {
  281. return (strlen((string)$data->$field) == 15);
  282. } elseif ($contentExpected == "A_NUMBER") {
  283. return is_numeric((string)$data->$field);
  284. } elseif ($contentExpected == "AN_URL") {
  285. return $this->isExpectedUrl((string)$data->$field, "index.php/s/");
  286. } elseif ($contentExpected == $data->$field) {
  287. return true;
  288. }
  289. return false;
  290. }
  291. }
  292. /**
  293. * @Then /^File "([^"]*)" should be included in the response$/
  294. *
  295. * @param string $filename
  296. */
  297. public function checkSharedFileInResponse($filename) {
  298. Assert::assertEquals(true, $this->isFieldInResponse('file_target', "/$filename"));
  299. }
  300. /**
  301. * @Then /^File "([^"]*)" should not be included in the response$/
  302. *
  303. * @param string $filename
  304. */
  305. public function checkSharedFileNotInResponse($filename) {
  306. Assert::assertEquals(false, $this->isFieldInResponse('file_target', "/$filename"));
  307. }
  308. /**
  309. * @Then /^User "([^"]*)" should be included in the response$/
  310. *
  311. * @param string $user
  312. */
  313. public function checkSharedUserInResponse($user) {
  314. Assert::assertEquals(true, $this->isFieldInResponse('share_with', "$user"));
  315. }
  316. /**
  317. * @Then /^User "([^"]*)" should not be included in the response$/
  318. *
  319. * @param string $user
  320. */
  321. public function checkSharedUserNotInResponse($user) {
  322. Assert::assertEquals(false, $this->isFieldInResponse('share_with', "$user"));
  323. }
  324. public function isUserOrGroupInSharedData($userOrGroup, $permissions = null) {
  325. $data = simplexml_load_string($this->response->getBody())->data[0];
  326. foreach ($data as $element) {
  327. if ($element->share_with == $userOrGroup && ($permissions === null || $permissions == $element->permissions)) {
  328. return true;
  329. }
  330. }
  331. return false;
  332. }
  333. /**
  334. * @Given /^(file|folder|entry) "([^"]*)" of user "([^"]*)" is shared with user "([^"]*)"( with permissions ([\d]*))?( view-only)?$/
  335. *
  336. * @param string $filepath
  337. * @param string $user1
  338. * @param string $user2
  339. */
  340. public function assureFileIsShared($entry, $filepath, $user1, $user2, $withPerms = null, $permissions = null, $viewOnly = null) {
  341. // when view-only is set, permissions is empty string instead of null...
  342. if ($permissions === '') {
  343. $permissions = null;
  344. }
  345. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares" . "?path=$filepath";
  346. $client = new Client();
  347. $options = [];
  348. if ($user1 === 'admin') {
  349. $options['auth'] = $this->adminUser;
  350. } else {
  351. $options['auth'] = [$user1, $this->regularUser];
  352. }
  353. $options['headers'] = [
  354. 'OCS-APIREQUEST' => 'true',
  355. ];
  356. $this->response = $client->get($fullUrl, $options);
  357. if ($this->isUserOrGroupInSharedData($user2, $permissions)) {
  358. return;
  359. } else {
  360. $this->createShare($user1, $filepath, 0, $user2, null, null, $permissions, $viewOnly !== null);
  361. }
  362. $this->response = $client->get($fullUrl, $options);
  363. Assert::assertEquals(true, $this->isUserOrGroupInSharedData($user2, $permissions));
  364. }
  365. /**
  366. * @Given /^(file|folder|entry) "([^"]*)" of user "([^"]*)" is shared with group "([^"]*)"( with permissions ([\d]*))?( view-only)?$/
  367. *
  368. * @param string $filepath
  369. * @param string $user
  370. * @param string $group
  371. */
  372. public function assureFileIsSharedWithGroup($entry, $filepath, $user, $group, $withPerms = null, $permissions = null, $viewOnly = null) {
  373. // when view-only is set, permissions is empty string instead of null...
  374. if ($permissions === '') {
  375. $permissions = null;
  376. }
  377. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares" . "?path=$filepath";
  378. $client = new Client();
  379. $options = [];
  380. if ($user === 'admin') {
  381. $options['auth'] = $this->adminUser;
  382. } else {
  383. $options['auth'] = [$user, $this->regularUser];
  384. }
  385. $options['headers'] = [
  386. 'OCS-APIREQUEST' => 'true',
  387. ];
  388. $this->response = $client->get($fullUrl, $options);
  389. if ($this->isUserOrGroupInSharedData($group, $permissions)) {
  390. return;
  391. } else {
  392. $this->createShare($user, $filepath, 1, $group, null, null, $permissions, $viewOnly !== null);
  393. }
  394. $this->response = $client->get($fullUrl, $options);
  395. Assert::assertEquals(true, $this->isUserOrGroupInSharedData($group, $permissions));
  396. }
  397. /**
  398. * @When /^Deleting last share$/
  399. */
  400. public function deletingLastShare() {
  401. $share_id = $this->lastShareData->data[0]->id;
  402. $url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  403. $this->sendingToWith("DELETE", $url, null);
  404. }
  405. /**
  406. * @When /^Getting info of last share$/
  407. */
  408. public function gettingInfoOfLastShare() {
  409. $share_id = $this->lastShareData->data[0]->id;
  410. $url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  411. $this->sendingToWith("GET", $url, null);
  412. }
  413. /**
  414. * @Then /^last share_id is included in the answer$/
  415. */
  416. public function checkingLastShareIDIsIncluded() {
  417. $share_id = $this->lastShareData->data[0]->id;
  418. if (!$this->isFieldInResponse('id', $share_id)) {
  419. Assert::fail("Share id $share_id not found in response");
  420. }
  421. }
  422. /**
  423. * @Then /^last share_id is not included in the answer$/
  424. */
  425. public function checkingLastShareIDIsNotIncluded() {
  426. $share_id = $this->lastShareData->data[0]->id;
  427. if ($this->isFieldInResponse('id', $share_id)) {
  428. Assert::fail("Share id $share_id has been found in response");
  429. }
  430. }
  431. /**
  432. * @Then /^Share fields of last share match with$/
  433. * @param TableNode|null $body
  434. */
  435. public function checkShareFields($body) {
  436. if ($body instanceof TableNode) {
  437. $fd = $body->getRowsHash();
  438. foreach ($fd as $field => $value) {
  439. if (substr($field, 0, 10) === "share_with") {
  440. $value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -5), $value);
  441. $value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -5), $value);
  442. }
  443. if (substr($field, 0, 6) === "remote") {
  444. $value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -4), $value);
  445. $value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -4), $value);
  446. }
  447. if (!$this->isFieldInResponse($field, $value)) {
  448. Assert::fail("$field" . " doesn't have value " . "$value");
  449. }
  450. }
  451. }
  452. }
  453. /**
  454. * @Then the list of returned shares has :count shares
  455. */
  456. public function theListOfReturnedSharesHasShares(int $count) {
  457. $this->theHTTPStatusCodeShouldBe('200');
  458. $this->theOCSStatusCodeShouldBe('100');
  459. $returnedShares = $this->getXmlResponse()->data[0];
  460. Assert::assertEquals($count, count($returnedShares->element));
  461. }
  462. /**
  463. * @Then share :count is returned with
  464. *
  465. * @param int $number
  466. * @param TableNode $body
  467. */
  468. public function shareXIsReturnedWith(int $number, TableNode $body) {
  469. $this->theHTTPStatusCodeShouldBe('200');
  470. $this->theOCSStatusCodeShouldBe('100');
  471. if (!($body instanceof TableNode)) {
  472. return;
  473. }
  474. $returnedShare = $this->getXmlResponse()->data[0];
  475. if ($returnedShare->element) {
  476. $returnedShare = $returnedShare->element[$number];
  477. }
  478. $defaultExpectedFields = [
  479. 'id' => 'A_NUMBER',
  480. 'permissions' => '19',
  481. 'stime' => 'A_NUMBER',
  482. 'parent' => '',
  483. 'expiration' => '',
  484. 'token' => '',
  485. 'storage' => 'A_NUMBER',
  486. 'item_source' => 'A_NUMBER',
  487. 'file_source' => 'A_NUMBER',
  488. 'file_parent' => 'A_NUMBER',
  489. 'mail_send' => '0'
  490. ];
  491. $expectedFields = array_merge($defaultExpectedFields, $body->getRowsHash());
  492. if (!array_key_exists('uid_file_owner', $expectedFields) &&
  493. array_key_exists('uid_owner', $expectedFields)) {
  494. $expectedFields['uid_file_owner'] = $expectedFields['uid_owner'];
  495. }
  496. if (!array_key_exists('displayname_file_owner', $expectedFields) &&
  497. array_key_exists('displayname_owner', $expectedFields)) {
  498. $expectedFields['displayname_file_owner'] = $expectedFields['displayname_owner'];
  499. }
  500. if (array_key_exists('share_type', $expectedFields) &&
  501. $expectedFields['share_type'] == 10 /* IShare::TYPE_ROOM */ &&
  502. array_key_exists('share_with', $expectedFields)) {
  503. if ($expectedFields['share_with'] === 'private_conversation') {
  504. $expectedFields['share_with'] = 'REGEXP /^private_conversation_[0-9a-f]{6}$/';
  505. } else {
  506. $expectedFields['share_with'] = FeatureContext::getTokenForIdentifier($expectedFields['share_with']);
  507. }
  508. }
  509. foreach ($expectedFields as $field => $value) {
  510. $this->assertFieldIsInReturnedShare($field, $value, $returnedShare);
  511. }
  512. }
  513. /**
  514. * @return SimpleXMLElement
  515. */
  516. private function getXmlResponse(): \SimpleXMLElement {
  517. return simplexml_load_string($this->response->getBody());
  518. }
  519. /**
  520. * @param string $field
  521. * @param string $contentExpected
  522. * @param \SimpleXMLElement $returnedShare
  523. */
  524. private function assertFieldIsInReturnedShare(string $field, string $contentExpected, \SimpleXMLElement $returnedShare) {
  525. if ($contentExpected === 'IGNORE') {
  526. return;
  527. }
  528. if (!property_exists($returnedShare, $field)) {
  529. Assert::fail("$field was not found in response");
  530. }
  531. if ($field === 'expiration' && !empty($contentExpected)) {
  532. $contentExpected = date('Y-m-d', strtotime($contentExpected)) . " 00:00:00";
  533. }
  534. if ($contentExpected === 'A_NUMBER') {
  535. Assert::assertTrue(is_numeric((string)$returnedShare->$field), "Field '$field' is not a number: " . $returnedShare->$field);
  536. } elseif ($contentExpected === 'A_TOKEN') {
  537. // A token is composed by 15 characters from
  538. // ISecureRandom::CHAR_HUMAN_READABLE.
  539. Assert::assertRegExp('/^[abcdefgijkmnopqrstwxyzABCDEFGHJKLMNPQRSTWXYZ23456789]{15}$/', (string)$returnedShare->$field, "Field '$field' is not a token");
  540. } elseif (strpos($contentExpected, 'REGEXP ') === 0) {
  541. Assert::assertRegExp(substr($contentExpected, strlen('REGEXP ')), (string)$returnedShare->$field, "Field '$field' does not match");
  542. } else {
  543. Assert::assertEquals($contentExpected, (string)$returnedShare->$field, "Field '$field' does not match");
  544. }
  545. }
  546. /**
  547. * @Then As :user remove all shares from the file named :fileName
  548. */
  549. public function asRemoveAllSharesFromTheFileNamed($user, $fileName) {
  550. $url = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares?format=json";
  551. $client = new \GuzzleHttp\Client();
  552. $res = $client->get(
  553. $url,
  554. [
  555. 'auth' => [
  556. $user,
  557. '123456',
  558. ],
  559. 'headers' => [
  560. 'Content-Type' => 'application/json',
  561. 'OCS-APIREQUEST' => 'true',
  562. ],
  563. ]
  564. );
  565. $json = json_decode($res->getBody()->getContents(), true);
  566. $deleted = false;
  567. foreach ($json['ocs']['data'] as $data) {
  568. if (stripslashes($data['path']) === $fileName) {
  569. $id = $data['id'];
  570. $client->delete(
  571. $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/{$id}",
  572. [
  573. 'auth' => [
  574. $user,
  575. '123456',
  576. ],
  577. 'headers' => [
  578. 'Content-Type' => 'application/json',
  579. 'OCS-APIREQUEST' => 'true',
  580. ],
  581. ]
  582. );
  583. $deleted = true;
  584. }
  585. }
  586. if ($deleted === false) {
  587. throw new \Exception("Could not delete file $fileName");
  588. }
  589. }
  590. /**
  591. * @When save last share id
  592. */
  593. public function saveLastShareId() {
  594. $this->savedShareId = ($this->lastShareData['data']['id'] ?? null);
  595. }
  596. /**
  597. * @Then share ids should match
  598. */
  599. public function shareIdsShouldMatch() {
  600. if ($this->savedShareId !== ($this->lastShareData['data']['id'] ?? null)) {
  601. throw new \Exception('Expected the same link share to be returned');
  602. }
  603. }
  604. /**
  605. * @When /^getting sharees for$/
  606. * @param TableNode $body
  607. */
  608. public function whenGettingShareesFor($body) {
  609. $url = '/apps/files_sharing/api/v1/sharees';
  610. if ($body instanceof TableNode) {
  611. $parameters = [];
  612. foreach ($body->getRowsHash() as $key => $value) {
  613. $parameters[] = $key . '=' . $value;
  614. }
  615. if (!empty($parameters)) {
  616. $url .= '?' . implode('&', $parameters);
  617. }
  618. }
  619. $this->sendingTo('GET', $url);
  620. }
  621. /**
  622. * @Then /^"([^"]*)" sharees returned (are|is empty)$/
  623. * @param string $shareeType
  624. * @param string $isEmpty
  625. * @param TableNode|null $shareesList
  626. */
  627. public function thenListOfSharees($shareeType, $isEmpty, $shareesList = null) {
  628. if ($isEmpty !== 'is empty') {
  629. $sharees = $shareesList->getRows();
  630. $respondedArray = $this->getArrayOfShareesResponded($this->response, $shareeType);
  631. Assert::assertEquals($sharees, $respondedArray);
  632. } else {
  633. $respondedArray = $this->getArrayOfShareesResponded($this->response, $shareeType);
  634. Assert::assertEmpty($respondedArray);
  635. }
  636. }
  637. public function getArrayOfShareesResponded(ResponseInterface $response, $shareeType) {
  638. $elements = simplexml_load_string($response->getBody())->data;
  639. $elements = json_decode(json_encode($elements), 1);
  640. if (strpos($shareeType, 'exact ') === 0) {
  641. $elements = $elements['exact'];
  642. $shareeType = substr($shareeType, 6);
  643. }
  644. $sharees = [];
  645. foreach ($elements[$shareeType] as $element) {
  646. $sharees[] = [$element['label'], $element['value']['shareType'], $element['value']['shareWith']];
  647. }
  648. return $sharees;
  649. }
  650. }