Sharing.php 23 KB

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