You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Sharing.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. <?php
  2. /**
  3. *
  4. *
  5. * @author Joas Schilling <coding@schilljs.com>
  6. * @author Lukas Reschke <lukas@statuscode.ch>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. * @author Sergio Bertolin <sbertolin@solidgear.es>
  9. * @author Sergio Bertolín <sbertolin@solidgear.es>
  10. * @author Vincent Petry <pvince81@owncloud.com>
  11. *
  12. * @license GNU AGPL version 3 or any later version
  13. *
  14. * This program is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License as
  16. * published by the Free Software Foundation, either version 3 of the
  17. * License, or (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  26. *
  27. */
  28. use GuzzleHttp\Client;
  29. use GuzzleHttp\Message\ResponseInterface;
  30. use PHPUnit\Framework\Assert;
  31. require __DIR__ . '/../../vendor/autoload.php';
  32. trait Sharing {
  33. use Provisioning;
  34. /** @var int */
  35. private $sharingApiVersion = 1;
  36. /** @var SimpleXMLElement */
  37. private $lastShareData = null;
  38. /** @var SimpleXMLElement[] */
  39. private $storedShareData = [];
  40. /** @var int */
  41. private $savedShareId = null;
  42. /** @var \Psr\Http\Message\ResponseInterface */
  43. private $response;
  44. /**
  45. * @Given /^as "([^"]*)" creating a share with$/
  46. * @param string $user
  47. * @param \Behat\Gherkin\Node\TableNode|null $body
  48. */
  49. public function asCreatingAShareWith($user, $body) {
  50. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares";
  51. $client = new Client();
  52. $options = [
  53. 'headers' => [
  54. 'OCS-APIREQUEST' => 'true',
  55. ],
  56. ];
  57. if ($user === 'admin') {
  58. $options['auth'] = $this->adminUser;
  59. } else {
  60. $options['auth'] = [$user, $this->regularUser];
  61. }
  62. if ($body instanceof \Behat\Gherkin\Node\TableNode) {
  63. $fd = $body->getRowsHash();
  64. if (array_key_exists('expireDate', $fd)){
  65. $dateModification = $fd['expireDate'];
  66. $fd['expireDate'] = date('Y-m-d', strtotime($dateModification));
  67. }
  68. $options['form_params'] = $fd;
  69. }
  70. try {
  71. $this->response = $client->request("POST", $fullUrl, $options);
  72. } catch (\GuzzleHttp\Exception\ClientException $ex) {
  73. $this->response = $ex->getResponse();
  74. }
  75. $this->lastShareData = simplexml_load_string($this->response->getBody());
  76. }
  77. /**
  78. * @When /^save the last share data as "([^"]*)"$/
  79. */
  80. public function saveLastShareData($name) {
  81. $this->storedShareData[$name] = $this->lastShareData;
  82. }
  83. /**
  84. * @When /^restore the last share data from "([^"]*)"$/
  85. */
  86. public function restoreLastShareData($name) {
  87. $this->lastShareData = $this->storedShareData[$name];
  88. }
  89. /**
  90. * @When /^creating a share with$/
  91. * @param \Behat\Gherkin\Node\TableNode|null $body
  92. */
  93. public function creatingShare($body) {
  94. $this->asCreatingAShareWith($this->currentUser, $body);
  95. }
  96. /**
  97. * @Then /^Public shared file "([^"]*)" can be downloaded$/
  98. */
  99. public function checkPublicSharedFile($filename) {
  100. $client = new Client();
  101. $options = [];
  102. if (count($this->lastShareData->data->element) > 0){
  103. $url = $this->lastShareData->data[0]->url;
  104. }
  105. else{
  106. $url = $this->lastShareData->data->url;
  107. }
  108. $fullUrl = $url . "/download";
  109. $this->checkDownload($fullUrl, null, 'text/plain');
  110. }
  111. /**
  112. * @Then /^Public shared file "([^"]*)" with password "([^"]*)" can be downloaded$/
  113. */
  114. public function checkPublicSharedFileWithPassword($filename, $password) {
  115. $options = [];
  116. if (count($this->lastShareData->data->element) > 0){
  117. $token = $this->lastShareData->data[0]->token;
  118. }
  119. else{
  120. $token = $this->lastShareData->data->token;
  121. }
  122. $fullUrl = substr($this->baseUrl, 0, -4) . "public.php/webdav";
  123. $this->checkDownload($fullUrl, [$token, $password], 'text/plain');
  124. }
  125. private function checkDownload($url, $auth = null, $mimeType = null) {
  126. if ($auth !== null) {
  127. $options['auth'] = $auth;
  128. }
  129. $options['stream'] = true;
  130. $client = new Client();
  131. $this->response = $client->get($url, $options);
  132. Assert::assertEquals(200, $this->response->getStatusCode());
  133. $buf = '';
  134. $body = $this->response->getBody();
  135. while (!$body->eof()) {
  136. // read everything
  137. $buf .= $body->read(8192);
  138. }
  139. $body->close();
  140. if ($mimeType !== null) {
  141. $finfo = new finfo;
  142. Assert::assertEquals($mimeType, $finfo->buffer($buf, FILEINFO_MIME_TYPE));
  143. }
  144. }
  145. /**
  146. * @When /^Adding expiration date to last share$/
  147. */
  148. public function addingExpirationDate() {
  149. $share_id = (string) $this->lastShareData->data[0]->id;
  150. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  151. $client = new Client();
  152. $options = [];
  153. if ($this->currentUser === 'admin') {
  154. $options['auth'] = $this->adminUser;
  155. } else {
  156. $options['auth'] = [$this->currentUser, $this->regularUser];
  157. }
  158. $date = date('Y-m-d', strtotime("+3 days"));
  159. $options['form_params'] = ['expireDate' => $date];
  160. $this->response = $this->response = $client->request("PUT", $fullUrl, $options);
  161. Assert::assertEquals(200, $this->response->getStatusCode());
  162. }
  163. /**
  164. * @When /^Updating last share with$/
  165. * @param \Behat\Gherkin\Node\TableNode|null $body
  166. */
  167. public function updatingLastShare($body) {
  168. $share_id = (string) $this->lastShareData->data[0]->id;
  169. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  170. $client = new Client();
  171. $options = [
  172. 'headers' => [
  173. 'OCS-APIREQUEST' => 'true',
  174. ],
  175. ];
  176. if ($this->currentUser === 'admin') {
  177. $options['auth'] = $this->adminUser;
  178. } else {
  179. $options['auth'] = [$this->currentUser, $this->regularUser];
  180. }
  181. if ($body instanceof \Behat\Gherkin\Node\TableNode) {
  182. $fd = $body->getRowsHash();
  183. if (array_key_exists('expireDate', $fd)){
  184. $dateModification = $fd['expireDate'];
  185. $fd['expireDate'] = date('Y-m-d', strtotime($dateModification));
  186. }
  187. $options['form_params'] = $fd;
  188. }
  189. try {
  190. $this->response = $client->request("PUT", $fullUrl, $options);
  191. } catch (\GuzzleHttp\Exception\ClientException $ex) {
  192. $this->response = $ex->getResponse();
  193. }
  194. Assert::assertEquals(200, $this->response->getStatusCode());
  195. }
  196. public function createShare($user,
  197. $path = null,
  198. $shareType = null,
  199. $shareWith = null,
  200. $publicUpload = null,
  201. $password = null,
  202. $permissions = null){
  203. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares";
  204. $client = new Client();
  205. $options = [
  206. 'headers' => [
  207. 'OCS-APIREQUEST' => 'true',
  208. ],
  209. ];
  210. if ($user === 'admin') {
  211. $options['auth'] = $this->adminUser;
  212. } else {
  213. $options['auth'] = [$user, $this->regularUser];
  214. }
  215. $body = [];
  216. if (!is_null($path)){
  217. $body['path'] = $path;
  218. }
  219. if (!is_null($shareType)){
  220. $body['shareType'] = $shareType;
  221. }
  222. if (!is_null($shareWith)){
  223. $body['shareWith'] = $shareWith;
  224. }
  225. if (!is_null($publicUpload)){
  226. $body['publicUpload'] = $publicUpload;
  227. }
  228. if (!is_null($password)){
  229. $body['password'] = $password;
  230. }
  231. if (!is_null($permissions)){
  232. $body['permissions'] = $permissions;
  233. }
  234. $options['form_params'] = $body;
  235. try {
  236. $this->response = $client->request("POST", $fullUrl, $options);
  237. $this->lastShareData = simplexml_load_string($this->response->getBody());
  238. } catch (\GuzzleHttp\Exception\ClientException $ex) {
  239. $this->response = $ex->getResponse();
  240. throw new \Exception($this->response->getBody());
  241. }
  242. }
  243. public function isFieldInResponse($field, $contentExpected){
  244. $data = simplexml_load_string($this->response->getBody())->data[0];
  245. if ((string)$field == 'expiration'){
  246. $contentExpected = date('Y-m-d', strtotime($contentExpected)) . " 00:00:00";
  247. }
  248. if (count($data->element) > 0){
  249. foreach($data as $element) {
  250. if ($contentExpected == "A_TOKEN"){
  251. return (strlen((string)$element->$field) == 15);
  252. }
  253. elseif ($contentExpected == "A_NUMBER"){
  254. return is_numeric((string)$element->$field);
  255. }
  256. elseif($contentExpected == "AN_URL"){
  257. return $this->isExpectedUrl((string)$element->$field, "index.php/s/");
  258. }
  259. elseif ((string)$element->$field == $contentExpected){
  260. return True;
  261. }
  262. else{
  263. print($element->$field);
  264. }
  265. }
  266. return False;
  267. } else {
  268. if ($contentExpected == "A_TOKEN"){
  269. return (strlen((string)$data->$field) == 15);
  270. }
  271. elseif ($contentExpected == "A_NUMBER"){
  272. return is_numeric((string)$data->$field);
  273. }
  274. elseif($contentExpected == "AN_URL"){
  275. return $this->isExpectedUrl((string)$data->$field, "index.php/s/");
  276. }
  277. elseif ($data->$field == $contentExpected){
  278. return True;
  279. }
  280. return False;
  281. }
  282. }
  283. /**
  284. * @Then /^File "([^"]*)" should be included in the response$/
  285. *
  286. * @param string $filename
  287. */
  288. public function checkSharedFileInResponse($filename){
  289. Assert::assertEquals(True, $this->isFieldInResponse('file_target', "/$filename"));
  290. }
  291. /**
  292. * @Then /^File "([^"]*)" should not be included in the response$/
  293. *
  294. * @param string $filename
  295. */
  296. public function checkSharedFileNotInResponse($filename){
  297. Assert::assertEquals(False, $this->isFieldInResponse('file_target', "/$filename"));
  298. }
  299. /**
  300. * @Then /^User "([^"]*)" should be included in the response$/
  301. *
  302. * @param string $user
  303. */
  304. public function checkSharedUserInResponse($user){
  305. Assert::assertEquals(True, $this->isFieldInResponse('share_with', "$user"));
  306. }
  307. /**
  308. * @Then /^User "([^"]*)" should not be included in the response$/
  309. *
  310. * @param string $user
  311. */
  312. public function checkSharedUserNotInResponse($user){
  313. Assert::assertEquals(False, $this->isFieldInResponse('share_with', "$user"));
  314. }
  315. public function isUserOrGroupInSharedData($userOrGroup, $permissions = null){
  316. $data = simplexml_load_string($this->response->getBody())->data[0];
  317. foreach($data as $element) {
  318. if ($element->share_with == $userOrGroup && ($permissions === null || $permissions == $element->permissions)){
  319. return True;
  320. }
  321. }
  322. return False;
  323. }
  324. /**
  325. * @Given /^(file|folder|entry) "([^"]*)" of user "([^"]*)" is shared with user "([^"]*)"( with permissions ([\d]*))?$/
  326. *
  327. * @param string $filepath
  328. * @param string $user1
  329. * @param string $user2
  330. */
  331. public function assureFileIsShared($entry, $filepath, $user1, $user2, $withPerms = null, $permissions = null){
  332. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares" . "?path=$filepath";
  333. $client = new Client();
  334. $options = [];
  335. if ($user1 === 'admin') {
  336. $options['auth'] = $this->adminUser;
  337. } else {
  338. $options['auth'] = [$user1, $this->regularUser];
  339. }
  340. $options['headers'] = [
  341. 'OCS-APIREQUEST' => 'true',
  342. ];
  343. $this->response = $client->get($fullUrl, $options);
  344. if ($this->isUserOrGroupInSharedData($user2, $permissions)){
  345. return;
  346. } else {
  347. $this->createShare($user1, $filepath, 0, $user2, null, null, $permissions);
  348. }
  349. $this->response = $client->get($fullUrl, $options);
  350. Assert::assertEquals(True, $this->isUserOrGroupInSharedData($user2, $permissions));
  351. }
  352. /**
  353. * @Given /^(file|folder|entry) "([^"]*)" of user "([^"]*)" is shared with group "([^"]*)"( with permissions ([\d]*))?$/
  354. *
  355. * @param string $filepath
  356. * @param string $user
  357. * @param string $group
  358. */
  359. public function assureFileIsSharedWithGroup($entry, $filepath, $user, $group, $withPerms = null, $permissions = null){
  360. $fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares" . "?path=$filepath";
  361. $client = new Client();
  362. $options = [];
  363. if ($user === 'admin') {
  364. $options['auth'] = $this->adminUser;
  365. } else {
  366. $options['auth'] = [$user, $this->regularUser];
  367. }
  368. $options['headers'] = [
  369. 'OCS-APIREQUEST' => 'true',
  370. ];
  371. $this->response = $client->get($fullUrl, $options);
  372. if ($this->isUserOrGroupInSharedData($group, $permissions)){
  373. return;
  374. } else {
  375. $this->createShare($user, $filepath, 1, $group, null, null, $permissions);
  376. }
  377. $this->response = $client->get($fullUrl, $options);
  378. Assert::assertEquals(True, $this->isUserOrGroupInSharedData($group, $permissions));
  379. }
  380. /**
  381. * @When /^Deleting last share$/
  382. */
  383. public function deletingLastShare(){
  384. $share_id = $this->lastShareData->data[0]->id;
  385. $url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  386. $this->sendingToWith("DELETE", $url, null);
  387. }
  388. /**
  389. * @When /^Getting info of last share$/
  390. */
  391. public function gettingInfoOfLastShare(){
  392. $share_id = $this->lastShareData->data[0]->id;
  393. $url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
  394. $this->sendingToWith("GET", $url, null);
  395. }
  396. /**
  397. * @Then /^last share_id is included in the answer$/
  398. */
  399. public function checkingLastShareIDIsIncluded(){
  400. $share_id = $this->lastShareData->data[0]->id;
  401. if (!$this->isFieldInResponse('id', $share_id)){
  402. Assert::fail("Share id $share_id not found in response");
  403. }
  404. }
  405. /**
  406. * @Then /^last share_id is not included in the answer$/
  407. */
  408. public function checkingLastShareIDIsNotIncluded(){
  409. $share_id = $this->lastShareData->data[0]->id;
  410. if ($this->isFieldInResponse('id', $share_id)){
  411. Assert::fail("Share id $share_id has been found in response");
  412. }
  413. }
  414. /**
  415. * @Then /^Share fields of last share match with$/
  416. * @param \Behat\Gherkin\Node\TableNode|null $body
  417. */
  418. public function checkShareFields($body){
  419. if ($body instanceof \Behat\Gherkin\Node\TableNode) {
  420. $fd = $body->getRowsHash();
  421. foreach($fd as $field => $value) {
  422. if (substr($field, 0, 10 ) === "share_with"){
  423. $value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -5), $value);
  424. $value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -5), $value);
  425. }
  426. if (substr($field, 0, 6 ) === "remote"){
  427. $value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -4), $value);
  428. $value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -4), $value);
  429. }
  430. if (!$this->isFieldInResponse($field, $value)){
  431. Assert::fail("$field" . " doesn't have value " . "$value");
  432. }
  433. }
  434. }
  435. }
  436. /**
  437. * @Then As :user remove all shares from the file named :fileName
  438. */
  439. public function asRemoveAllSharesFromTheFileNamed($user, $fileName) {
  440. $url = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares?format=json";
  441. $client = new \GuzzleHttp\Client();
  442. $res = $client->get(
  443. $url,
  444. [
  445. 'auth' => [
  446. $user,
  447. '123456',
  448. ],
  449. 'headers' => [
  450. 'Content-Type' => 'application/json',
  451. 'OCS-APIREQUEST' => 'true',
  452. ],
  453. ]
  454. );
  455. $json = json_decode($res->getBody()->getContents(), true);
  456. $deleted = false;
  457. foreach($json['ocs']['data'] as $data) {
  458. if (stripslashes($data['path']) === $fileName) {
  459. $id = $data['id'];
  460. $client->delete(
  461. $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/{$id}",
  462. [
  463. 'auth' => [
  464. $user,
  465. '123456',
  466. ],
  467. 'headers' => [
  468. 'Content-Type' => 'application/json',
  469. 'OCS-APIREQUEST' => 'true',
  470. ],
  471. ]
  472. );
  473. $deleted = true;
  474. }
  475. }
  476. if($deleted === false) {
  477. throw new \Exception("Could not delete file $fileName");
  478. }
  479. }
  480. /**
  481. * @When save last share id
  482. */
  483. public function saveLastShareId()
  484. {
  485. $this->savedShareId = $this->lastShareData['data']['id'];
  486. }
  487. /**
  488. * @Then share ids should match
  489. */
  490. public function shareIdsShouldMatch()
  491. {
  492. if ($this->savedShareId !== $this->lastShareData['data']['id']) {
  493. throw new \Exception('Expected the same link share to be returned');
  494. }
  495. }
  496. /**
  497. * @Then The following headers should be set
  498. * @param \Behat\Gherkin\Node\TableNode $table
  499. * @throws \Exception
  500. */
  501. public function theFollowingHeadersShouldBeSet(\Behat\Gherkin\Node\TableNode $table) {
  502. foreach($table->getTable() as $header) {
  503. $headerName = $header[0];
  504. $expectedHeaderValue = $header[1];
  505. $returnedHeader = $this->response->getHeader($headerName)[0];
  506. if($returnedHeader !== $expectedHeaderValue) {
  507. throw new \Exception(
  508. sprintf(
  509. "Expected value '%s' for header '%s', got '%s'",
  510. $expectedHeaderValue,
  511. $headerName,
  512. $returnedHeader
  513. )
  514. );
  515. }
  516. }
  517. }
  518. }