Sharing.php 16 KB

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