Sharing.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares";
  243. $client = new Client();
  244. $options = [
  245. 'headers' => [
  246. 'OCS-APIREQUEST' => 'true',
  247. ],
  248. ];
  249. if ($user === 'admin') {
  250. $options['auth'] = $this->adminUser;
  251. } else {
  252. $options['auth'] = [$user, $this->regularUser];
  253. }
  254. $body = [];
  255. if (!is_null($path)) {
  256. $body['path'] = $path;
  257. }
  258. if (!is_null($shareType)) {
  259. $body['shareType'] = $shareType;
  260. }
  261. if (!is_null($shareWith)) {
  262. $body['shareWith'] = $shareWith;
  263. }
  264. if (!is_null($publicUpload)) {
  265. $body['publicUpload'] = $publicUpload;
  266. }
  267. if (!is_null($password)) {
  268. $body['password'] = $password;
  269. }
  270. if (!is_null($permissions)) {
  271. $body['permissions'] = $permissions;
  272. }
  273. $options['form_params'] = $body;
  274. try {
  275. $this->response = $client->request("POST", $fullUrl, $options);
  276. $this->lastShareData = simplexml_load_string($this->response->getBody());
  277. } catch (\GuzzleHttp\Exception\ClientException $ex) {
  278. $this->response = $ex->getResponse();
  279. throw new \Exception($this->response->getBody());
  280. }
  281. }
  282. public function isFieldInResponse($field, $contentExpected) {
  283. $data = simplexml_load_string($this->response->getBody())->data[0];
  284. if ((string)$field == 'expiration') {
  285. $contentExpected = date('Y-m-d', strtotime($contentExpected)) . " 00:00:00";
  286. }
  287. if (count($data->element) > 0) {
  288. foreach ($data as $element) {
  289. if ($contentExpected == "A_TOKEN") {
  290. return (strlen((string)$element->$field) == 15);
  291. } elseif ($contentExpected == "A_NUMBER") {
  292. return is_numeric((string)$element->$field);
  293. } elseif ($contentExpected == "AN_URL") {
  294. return $this->isExpectedUrl((string)$element->$field, "index.php/s/");
  295. } elseif ((string)$element->$field == $contentExpected) {
  296. return true;
  297. } else {
  298. print($element->$field);
  299. }
  300. }
  301. return false;
  302. } else {
  303. if ($contentExpected == "A_TOKEN") {
  304. return (strlen((string)$data->$field) == 15);
  305. } elseif ($contentExpected == "A_NUMBER") {
  306. return is_numeric((string)$data->$field);
  307. } elseif ($contentExpected == "AN_URL") {
  308. return $this->isExpectedUrl((string)$data->$field, "index.php/s/");
  309. } elseif ($data->$field == $contentExpected) {
  310. return true;
  311. }
  312. return false;
  313. }
  314. }
  315. /**
  316. * @Then /^File "([^"]*)" should be included in the response$/
  317. *
  318. * @param string $filename
  319. */
  320. public function checkSharedFileInResponse($filename) {
  321. Assert::assertEquals(true, $this->isFieldInResponse('file_target', "/$filename"));
  322. }
  323. /**
  324. * @Then /^File "([^"]*)" should not be included in the response$/
  325. *
  326. * @param string $filename
  327. */
  328. public function checkSharedFileNotInResponse($filename) {
  329. Assert::assertEquals(false, $this->isFieldInResponse('file_target', "/$filename"));
  330. }
  331. /**
  332. * @Then /^User "([^"]*)" should be included in the response$/
  333. *
  334. * @param string $user
  335. */
  336. public function checkSharedUserInResponse($user) {
  337. Assert::assertEquals(true, $this->isFieldInResponse('share_with', "$user"));
  338. }
  339. /**
  340. * @Then /^User "([^"]*)" should not be included in the response$/
  341. *
  342. * @param string $user
  343. */
  344. public function checkSharedUserNotInResponse($user) {
  345. Assert::assertEquals(false, $this->isFieldInResponse('share_with', "$user"));
  346. }
  347. public function isUserOrGroupInSharedData($userOrGroup, $permissions = null) {
  348. $data = simplexml_load_string($this->response->getBody())->data[0];
  349. foreach ($data as $element) {
  350. if ($element->share_with == $userOrGroup && ($permissions === null || $permissions == $element->permissions)) {
  351. return true;
  352. }
  353. }
  354. return false;
  355. }
  356. /**
  357. * @Given /^(file|folder|entry) "([^"]*)" of user "([^"]*)" is shared with user "([^"]*)"( with permissions ([\d]*))?$/
  358. *
  359. * @param string $filepath
  360. * @param string $user1
  361. * @param string $user2
  362. */
  363. public function assureFileIsShared($entry, $filepath, $user1, $user2, $withPerms = null, $permissions = null) {
  364. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares" . "?path=$filepath";
  365. $client = new Client();
  366. $options = [];
  367. if ($user1 === 'admin') {
  368. $options['auth'] = $this->adminUser;
  369. } else {
  370. $options['auth'] = [$user1, $this->regularUser];
  371. }
  372. $options['headers'] = [
  373. 'OCS-APIREQUEST' => 'true',
  374. ];
  375. $this->response = $client->get($fullUrl, $options);
  376. if ($this->isUserOrGroupInSharedData($user2, $permissions)) {
  377. return;
  378. } else {
  379. $this->createShare($user1, $filepath, 0, $user2, null, null, $permissions);
  380. }
  381. $this->response = $client->get($fullUrl, $options);
  382. Assert::assertEquals(true, $this->isUserOrGroupInSharedData($user2, $permissions));
  383. }
  384. /**
  385. * @Given /^(file|folder|entry) "([^"]*)" of user "([^"]*)" is shared with group "([^"]*)"( with permissions ([\d]*))?$/
  386. *
  387. * @param string $filepath
  388. * @param string $user
  389. * @param string $group
  390. */
  391. public function assureFileIsSharedWithGroup($entry, $filepath, $user, $group, $withPerms = null, $permissions = null) {
  392. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares" . "?path=$filepath";
  393. $client = new Client();
  394. $options = [];
  395. if ($user === 'admin') {
  396. $options['auth'] = $this->adminUser;
  397. } else {
  398. $options['auth'] = [$user, $this->regularUser];
  399. }
  400. $options['headers'] = [
  401. 'OCS-APIREQUEST' => 'true',
  402. ];
  403. $this->response = $client->get($fullUrl, $options);
  404. if ($this->isUserOrGroupInSharedData($group, $permissions)) {
  405. return;
  406. } else {
  407. $this->createShare($user, $filepath, 1, $group, null, null, $permissions);
  408. }
  409. $this->response = $client->get($fullUrl, $options);
  410. Assert::assertEquals(true, $this->isUserOrGroupInSharedData($group, $permissions));
  411. }
  412. /**
  413. * @When /^Deleting last share$/
  414. */
  415. public function deletingLastShare() {
  416. $share_id = $this->lastShareData->data[0]->id;
  417. $url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  418. $this->sendingToWith("DELETE", $url, null);
  419. }
  420. /**
  421. * @When /^Getting info of last share$/
  422. */
  423. public function gettingInfoOfLastShare() {
  424. $share_id = $this->lastShareData->data[0]->id;
  425. $url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  426. $this->sendingToWith("GET", $url, null);
  427. }
  428. /**
  429. * @Then /^last share_id is included in the answer$/
  430. */
  431. public function checkingLastShareIDIsIncluded() {
  432. $share_id = $this->lastShareData->data[0]->id;
  433. if (!$this->isFieldInResponse('id', $share_id)) {
  434. Assert::fail("Share id $share_id not found in response");
  435. }
  436. }
  437. /**
  438. * @Then /^last share_id is not included in the answer$/
  439. */
  440. public function checkingLastShareIDIsNotIncluded() {
  441. $share_id = $this->lastShareData->data[0]->id;
  442. if ($this->isFieldInResponse('id', $share_id)) {
  443. Assert::fail("Share id $share_id has been found in response");
  444. }
  445. }
  446. /**
  447. * @Then /^Share fields of last share match with$/
  448. * @param TableNode|null $body
  449. */
  450. public function checkShareFields($body) {
  451. if ($body instanceof TableNode) {
  452. $fd = $body->getRowsHash();
  453. foreach ($fd as $field => $value) {
  454. if (substr($field, 0, 10) === "share_with") {
  455. $value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -5), $value);
  456. $value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -5), $value);
  457. }
  458. if (substr($field, 0, 6) === "remote") {
  459. $value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -4), $value);
  460. $value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -4), $value);
  461. }
  462. if (!$this->isFieldInResponse($field, $value)) {
  463. Assert::fail("$field" . " doesn't have value " . "$value");
  464. }
  465. }
  466. }
  467. }
  468. /**
  469. * @Then the list of returned shares has :count shares
  470. */
  471. public function theListOfReturnedSharesHasShares(int $count) {
  472. $this->theHTTPStatusCodeShouldBe('200');
  473. $this->theOCSStatusCodeShouldBe('100');
  474. $returnedShares = $this->getXmlResponse()->data[0];
  475. Assert::assertEquals($count, count($returnedShares->element));
  476. }
  477. /**
  478. * @Then share :count is returned with
  479. *
  480. * @param int $number
  481. * @param TableNode $body
  482. */
  483. public function shareXIsReturnedWith(int $number, TableNode $body) {
  484. $this->theHTTPStatusCodeShouldBe('200');
  485. $this->theOCSStatusCodeShouldBe('100');
  486. if (!($body instanceof TableNode)) {
  487. return;
  488. }
  489. $returnedShare = $this->getXmlResponse()->data[0];
  490. if ($returnedShare->element) {
  491. $returnedShare = $returnedShare->element[$number];
  492. }
  493. $defaultExpectedFields = [
  494. 'id' => 'A_NUMBER',
  495. 'permissions' => '19',
  496. 'stime' => 'A_NUMBER',
  497. 'parent' => '',
  498. 'expiration' => '',
  499. 'token' => '',
  500. 'storage' => 'A_NUMBER',
  501. 'item_source' => 'A_NUMBER',
  502. 'file_source' => 'A_NUMBER',
  503. 'file_parent' => 'A_NUMBER',
  504. 'mail_send' => '0'
  505. ];
  506. $expectedFields = array_merge($defaultExpectedFields, $body->getRowsHash());
  507. if (!array_key_exists('uid_file_owner', $expectedFields) &&
  508. array_key_exists('uid_owner', $expectedFields)) {
  509. $expectedFields['uid_file_owner'] = $expectedFields['uid_owner'];
  510. }
  511. if (!array_key_exists('displayname_file_owner', $expectedFields) &&
  512. array_key_exists('displayname_owner', $expectedFields)) {
  513. $expectedFields['displayname_file_owner'] = $expectedFields['displayname_owner'];
  514. }
  515. if (array_key_exists('share_type', $expectedFields) &&
  516. $expectedFields['share_type'] == 10 /* IShare::TYPE_ROOM */ &&
  517. array_key_exists('share_with', $expectedFields)) {
  518. if ($expectedFields['share_with'] === 'private_conversation') {
  519. $expectedFields['share_with'] = 'REGEXP /^private_conversation_[0-9a-f]{6}$/';
  520. } else {
  521. $expectedFields['share_with'] = FeatureContext::getTokenForIdentifier($expectedFields['share_with']);
  522. }
  523. }
  524. foreach ($expectedFields as $field => $value) {
  525. $this->assertFieldIsInReturnedShare($field, $value, $returnedShare);
  526. }
  527. }
  528. /**
  529. * @return SimpleXMLElement
  530. */
  531. private function getXmlResponse(): \SimpleXMLElement {
  532. return simplexml_load_string($this->response->getBody());
  533. }
  534. /**
  535. * @param string $field
  536. * @param string $contentExpected
  537. * @param \SimpleXMLElement $returnedShare
  538. */
  539. private function assertFieldIsInReturnedShare(string $field, string $contentExpected, \SimpleXMLElement $returnedShare) {
  540. if ($contentExpected === 'IGNORE') {
  541. return;
  542. }
  543. if (!array_key_exists($field, $returnedShare)) {
  544. Assert::fail("$field was not found in response");
  545. }
  546. if ($field === 'expiration' && !empty($contentExpected)) {
  547. $contentExpected = date('Y-m-d', strtotime($contentExpected)) . " 00:00:00";
  548. }
  549. if ($contentExpected === 'A_NUMBER') {
  550. Assert::assertTrue(is_numeric((string)$returnedShare->$field), "Field '$field' is not a number: " . $returnedShare->$field);
  551. } elseif ($contentExpected === 'A_TOKEN') {
  552. // A token is composed by 15 characters from
  553. // ISecureRandom::CHAR_HUMAN_READABLE.
  554. Assert::assertRegExp('/^[abcdefgijkmnopqrstwxyzABCDEFGHJKLMNPQRSTWXYZ23456789]{15}$/', (string)$returnedShare->$field, "Field '$field' is not a token");
  555. } elseif (strpos($contentExpected, 'REGEXP ') === 0) {
  556. Assert::assertRegExp(substr($contentExpected, strlen('REGEXP ')), (string)$returnedShare->$field, "Field '$field' does not match");
  557. } else {
  558. Assert::assertEquals($contentExpected, (string)$returnedShare->$field, "Field '$field' does not match");
  559. }
  560. }
  561. /**
  562. * @Then As :user remove all shares from the file named :fileName
  563. */
  564. public function asRemoveAllSharesFromTheFileNamed($user, $fileName) {
  565. $url = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares?format=json";
  566. $client = new \GuzzleHttp\Client();
  567. $res = $client->get(
  568. $url,
  569. [
  570. 'auth' => [
  571. $user,
  572. '123456',
  573. ],
  574. 'headers' => [
  575. 'Content-Type' => 'application/json',
  576. 'OCS-APIREQUEST' => 'true',
  577. ],
  578. ]
  579. );
  580. $json = json_decode($res->getBody()->getContents(), true);
  581. $deleted = false;
  582. foreach ($json['ocs']['data'] as $data) {
  583. if (stripslashes($data['path']) === $fileName) {
  584. $id = $data['id'];
  585. $client->delete(
  586. $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/{$id}",
  587. [
  588. 'auth' => [
  589. $user,
  590. '123456',
  591. ],
  592. 'headers' => [
  593. 'Content-Type' => 'application/json',
  594. 'OCS-APIREQUEST' => 'true',
  595. ],
  596. ]
  597. );
  598. $deleted = true;
  599. }
  600. }
  601. if ($deleted === false) {
  602. throw new \Exception("Could not delete file $fileName");
  603. }
  604. }
  605. /**
  606. * @When save last share id
  607. */
  608. public function saveLastShareId() {
  609. $this->savedShareId = $this->lastShareData['data']['id'];
  610. }
  611. /**
  612. * @Then share ids should match
  613. */
  614. public function shareIdsShouldMatch() {
  615. if ($this->savedShareId !== $this->lastShareData['data']['id']) {
  616. throw new \Exception('Expected the same link share to be returned');
  617. }
  618. }
  619. /**
  620. * @When /^getting sharees for$/
  621. * @param TableNode $body
  622. */
  623. public function whenGettingShareesFor($body) {
  624. $url = '/apps/files_sharing/api/v1/sharees';
  625. if ($body instanceof TableNode) {
  626. $parameters = [];
  627. foreach ($body->getRowsHash() as $key => $value) {
  628. $parameters[] = $key . '=' . $value;
  629. }
  630. if (!empty($parameters)) {
  631. $url .= '?' . implode('&', $parameters);
  632. }
  633. }
  634. $this->sendingTo('GET', $url);
  635. }
  636. /**
  637. * @Then /^"([^"]*)" sharees returned (are|is empty)$/
  638. * @param string $shareeType
  639. * @param string $isEmpty
  640. * @param TableNode|null $shareesList
  641. */
  642. public function thenListOfSharees($shareeType, $isEmpty, $shareesList = null) {
  643. if ($isEmpty !== 'is empty') {
  644. $sharees = $shareesList->getRows();
  645. $respondedArray = $this->getArrayOfShareesResponded($this->response, $shareeType);
  646. Assert::assertEquals($sharees, $respondedArray);
  647. } else {
  648. $respondedArray = $this->getArrayOfShareesResponded($this->response, $shareeType);
  649. Assert::assertEmpty($respondedArray);
  650. }
  651. }
  652. public function getArrayOfShareesResponded(ResponseInterface $response, $shareeType) {
  653. $elements = simplexml_load_string($response->getBody())->data;
  654. $elements = json_decode(json_encode($elements), 1);
  655. if (strpos($shareeType, 'exact ') === 0) {
  656. $elements = $elements['exact'];
  657. $shareeType = substr($shareeType, 6);
  658. }
  659. $sharees = [];
  660. foreach ($elements[$shareeType] as $element) {
  661. $sharees[] = [$element['label'], $element['value']['shareType'], $element['value']['shareWith']];
  662. }
  663. return $sharees;
  664. }
  665. }