Sharing.php 22 KB

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