1
0

Sharing.php 23 KB

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