Sharing.php 16 KB

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