Sharing.php 17.4 KB
Newer Older
1 2 3 4 5
<?php

use GuzzleHttp\Client;
use GuzzleHttp\Message\ResponseInterface;

Sergio Bertolin's avatar
Sergio Bertolin committed
6
require __DIR__ . '/../../../../lib/composer/autoload.php';
7 8 9



10
trait Sharing {
Joas Schilling's avatar
Joas Schilling committed
11
	use Provisioning;
12 13 14 15 16 17 18

	/** @var int */
	private $sharingApiVersion = 1;

	/** @var SimpleXMLElement */
	private $lastShareData = null;

Roeland Jago Douma's avatar
Roeland Jago Douma committed
19 20 21
	/** @var int */
	private $savedShareId = null;

22
	/**
Vincent Petry's avatar
Vincent Petry committed
23
	 * @Given /^as "([^"]*)" creating a share with$/
Joas Schilling's avatar
Joas Schilling committed
24 25
	 * @param string $user
	 * @param \Behat\Gherkin\Node\TableNode|null $body
26
	 */
Vincent Petry's avatar
Vincent Petry committed
27
	public function asCreatingAShareWith($user, $body) {
Joas Schilling's avatar
Joas Schilling committed
28
		$fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares";
29 30
		$client = new Client();
		$options = [];
Vincent Petry's avatar
Vincent Petry committed
31
		if ($user === 'admin') {
32 33
			$options['auth'] = $this->adminUser;
		} else {
Vincent Petry's avatar
Vincent Petry committed
34
			$options['auth'] = [$user, $this->regularUser];
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
		}

		if ($body instanceof \Behat\Gherkin\Node\TableNode) {
			$fd = $body->getRowsHash();
			if (array_key_exists('expireDate', $fd)){
				$dateModification = $fd['expireDate'];
				$fd['expireDate'] = date('Y-m-d', strtotime($dateModification));
			}
			$options['body'] = $fd;
		}

		try {
			$this->response = $client->send($client->createRequest("POST", $fullUrl, $options));
		} catch (\GuzzleHttp\Exception\ClientException $ex) {
			$this->response = $ex->getResponse();
		}

		$this->lastShareData = $this->response->xml();
	}

Vincent Petry's avatar
Vincent Petry committed
55 56
	/**
	 * @When /^creating a share with$/
Joas Schilling's avatar
Joas Schilling committed
57
	 * @param \Behat\Gherkin\Node\TableNode|null $body
Vincent Petry's avatar
Vincent Petry committed
58 59
	 */
	public function creatingShare($body) {
60
		$this->asCreatingAShareWith($this->currentUser, $body);
Vincent Petry's avatar
Vincent Petry committed
61 62
	}

63 64 65 66 67 68 69 70 71 72 73 74 75
	/**
	 * @Then /^Public shared file "([^"]*)" can be downloaded$/
	 */
	public function checkPublicSharedFile($filename) {
		$client = new Client();
		$options = [];
		if (count($this->lastShareData->data->element) > 0){
			$url = $this->lastShareData->data[0]->url;
		}
		else{
			$url = $this->lastShareData->data->url;
		}
		$fullUrl = $url . "/download";
76
		$this->checkDownload($fullUrl, null, 'text/plain');
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	}

	/**
	 * @Then /^Public shared file "([^"]*)" with password "([^"]*)" can be downloaded$/
	 */
	public function checkPublicSharedFileWithPassword($filename, $password) {
		$options = [];
		if (count($this->lastShareData->data->element) > 0){
			$token = $this->lastShareData->data[0]->token;
		}
		else{
			$token = $this->lastShareData->data->token;
		}

		$fullUrl = substr($this->baseUrl, 0, -4) . "public.php/webdav";
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
		$this->checkDownload($fullUrl, [$token, $password], 'text/plain');
	}

	private function checkDownload($url, $auth = null, $mimeType = null) {
		if ($auth !== null) {
			$options['auth'] = $auth;
		}
		$options['stream'] = true;

		$client = new Client();
		$this->response = $client->get($url, $options);
		PHPUnit_Framework_Assert::assertEquals(200, $this->response->getStatusCode());

		$buf = '';
		$body = $this->response->getBody();
		while (!$body->eof()) {
			// read everything
			$buf .= $body->read(8192);
		}
		$body->close();

		if ($mimeType !== null) {
			$finfo = new finfo;
			PHPUnit_Framework_Assert::assertEquals($mimeType, $finfo->buffer($buf, FILEINFO_MIME_TYPE));
116 117 118 119 120 121 122
		}
	}

	/**
	 * @When /^Adding expiration date to last share$/
	 */
	public function addingExpirationDate() {
Joas Schilling's avatar
Joas Schilling committed
123
		$share_id = (string) $this->lastShareData->data[0]->id;
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
		$fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
		$client = new Client();
		$options = [];
		if ($this->currentUser === 'admin') {
			$options['auth'] = $this->adminUser;
		} else {
			$options['auth'] = [$this->currentUser, $this->regularUser];
		}
		$date = date('Y-m-d', strtotime("+3 days"));
		$options['body'] = ['expireDate' => $date];
		$this->response = $client->send($client->createRequest("PUT", $fullUrl, $options));
		PHPUnit_Framework_Assert::assertEquals(200, $this->response->getStatusCode());
	}

	/**
	 * @When /^Updating last share with$/
	 * @param \Behat\Gherkin\Node\TableNode|null $body
	 */
	public function updatingLastShare($body) {
Joas Schilling's avatar
Joas Schilling committed
143
		$share_id = (string) $this->lastShareData->data[0]->id;
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
		$fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
		$client = new Client();
		$options = [];
		if ($this->currentUser === 'admin') {
			$options['auth'] = $this->adminUser;
		} else {
			$options['auth'] = [$this->currentUser, $this->regularUser];
		}

		if ($body instanceof \Behat\Gherkin\Node\TableNode) {
			$fd = $body->getRowsHash();
			if (array_key_exists('expireDate', $fd)){
				$dateModification = $fd['expireDate'];
				$fd['expireDate'] = date('Y-m-d', strtotime($dateModification));
			}
			$options['body'] = $fd;
		}

		try {
			$this->response = $client->send($client->createRequest("PUT", $fullUrl, $options));
		} catch (\GuzzleHttp\Exception\ClientException $ex) {
			$this->response = $ex->getResponse();
		}

		PHPUnit_Framework_Assert::assertEquals(200, $this->response->getStatusCode());
	}

	public function createShare($user,
								$path = null,
								$shareType = null,
								$shareWith = null,
								$publicUpload = null,
								$password = null,
177 178
								$permissions = null,
								$linkName = null) {
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
		$fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares";
		$client = new Client();
		$options = [];

		if ($user === 'admin') {
			$options['auth'] = $this->adminUser;
		} else {
			$options['auth'] = [$user, $this->regularUser];
		}
		$fd = [];
		if (!is_null($path)){
			$fd['path'] = $path;
		}
		if (!is_null($shareType)){
			$fd['shareType'] = $shareType;
		}
		if (!is_null($shareWith)){
			$fd['shareWith'] = $shareWith;
		}
		if (!is_null($publicUpload)){
			$fd['publicUpload'] = $publicUpload;
		}
		if (!is_null($password)){
			$fd['password'] = $password;
		}
		if (!is_null($permissions)){
			$fd['permissions'] = $permissions;
		}
207 208 209
		if (!is_null($linkName)){
			$fd['name'] = $linkName;
		}
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

		$options['body'] = $fd;

		try {
			$this->response = $client->send($client->createRequest("POST", $fullUrl, $options));
			$this->lastShareData = $this->response->xml();
		} catch (\GuzzleHttp\Exception\ClientException $ex) {
			$this->response = $ex->getResponse();
		}
	}

	public function isFieldInResponse($field, $contentExpected){
		$data = $this->response->xml()->data[0];
		if ((string)$field == 'expiration'){
			$contentExpected = date('Y-m-d', strtotime($contentExpected)) . " 00:00:00";
		}
		if (count($data->element) > 0){
			foreach($data as $element) {
				if ($contentExpected == "A_TOKEN"){
					return (strlen((string)$element->$field) == 15);
				}
				elseif ($contentExpected == "A_NUMBER"){
					return is_numeric((string)$element->$field);
				}
				elseif($contentExpected == "AN_URL"){
					return $this->isExpectedUrl((string)$element->$field, "index.php/s/");
				}
				elseif ((string)$element->$field == $contentExpected){
					return True;
				}
240 241 242
				else{
					print($element->$field);
				}
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
			}

			return False;
		} else {
			if ($contentExpected == "A_TOKEN"){
					return (strlen((string)$data->$field) == 15);
			}
			elseif ($contentExpected == "A_NUMBER"){
					return is_numeric((string)$data->$field);
			}
			elseif($contentExpected == "AN_URL"){
					return $this->isExpectedUrl((string)$data->$field, "index.php/s/");
			}
			elseif ($data->$field == $contentExpected){
					return True;
			}
			return False;
		}
	}

	/**
	 * @Then /^File "([^"]*)" should be included in the response$/
Joas Schilling's avatar
Joas Schilling committed
265 266
	 *
	 * @param string $filename
267 268
	 */
	public function checkSharedFileInResponse($filename){
269
		$filename = ltrim($filename, '/');
270 271 272 273 274
		PHPUnit_Framework_Assert::assertEquals(True, $this->isFieldInResponse('file_target', "/$filename"));
	}

	/**
	 * @Then /^File "([^"]*)" should not be included in the response$/
Joas Schilling's avatar
Joas Schilling committed
275 276
	 *
	 * @param string $filename
277 278
	 */
	public function checkSharedFileNotInResponse($filename){
279
		$filename = ltrim($filename, '/');
280 281 282
		PHPUnit_Framework_Assert::assertEquals(False, $this->isFieldInResponse('file_target', "/$filename"));
	}

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	/**
	 * @Then /^File "([^"]*)" should be included as path in the response$/
	 *
	 * @param string $filename
	 */
	public function checkSharedFileAsPathInResponse($filename){
		$filename = ltrim($filename, '/');
		PHPUnit_Framework_Assert::assertEquals(True, $this->isFieldInResponse('path', "/$filename"));
	}

	/**
	 * @Then /^File "([^"]*)" should not be included as path in the response$/
	 *
	 * @param string $filename
	 */
	public function checkSharedFileAsPathNotInResponse($filename){
		$filename = ltrim($filename, '/');
		PHPUnit_Framework_Assert::assertEquals(False, $this->isFieldInResponse('path', "/$filename"));
	}

303 304
	/**
	 * @Then /^User "([^"]*)" should be included in the response$/
Joas Schilling's avatar
Joas Schilling committed
305 306
	 *
	 * @param string $user
307 308 309 310 311 312 313
	 */
	public function checkSharedUserInResponse($user){
		PHPUnit_Framework_Assert::assertEquals(True, $this->isFieldInResponse('share_with', "$user"));
	}

	/**
	 * @Then /^User "([^"]*)" should not be included in the response$/
Joas Schilling's avatar
Joas Schilling committed
314 315
	 *
	 * @param string $user
316 317 318 319 320
	 */
	public function checkSharedUserNotInResponse($user){
		PHPUnit_Framework_Assert::assertEquals(False, $this->isFieldInResponse('share_with', "$user"));
	}

321
	public function isUserOrGroupInSharedData($userOrGroup, $permissions = null){
322 323
		$data = $this->response->xml()->data[0];
		foreach($data as $element) {
324
			if ($element->share_with == $userOrGroup && ($permissions === null || $permissions == $element->permissions)){
325 326 327 328 329 330 331
				return True;
			}
		}
		return False;
	}

	/**
332
	 * @Given /^(file|folder|entry) "([^"]*)" of user "([^"]*)" is shared with user "([^"]*)"( with permissions ([\d]*))?$/
Joas Schilling's avatar
Joas Schilling committed
333 334 335 336
	 *
	 * @param string $filepath
	 * @param string $user1
	 * @param string $user2
337
	 */
338
	public function assureFileIsShared($entry, $filepath, $user1, $user2, $withPerms = null, $permissions = null){
339 340 341 342 343 344 345 346 347
		$fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares" . "?path=$filepath";
		$client = new Client();
		$options = [];
		if ($user1 === 'admin') {
			$options['auth'] = $this->adminUser;
		} else {
			$options['auth'] = [$user1, $this->regularUser];
		}
		$this->response = $client->get($fullUrl, $options);
348
		if ($this->isUserOrGroupInSharedData($user2, $permissions)){
349 350
			return;
		} else {
351
			$this->createShare($user1, $filepath, 0, $user2, null, null, $permissions);
352 353
		}
		$this->response = $client->get($fullUrl, $options);
354
		PHPUnit_Framework_Assert::assertEquals(True, $this->isUserOrGroupInSharedData($user2, $permissions));
355 356 357
	}

	/**
358
	 * @Given /^(file|folder|entry) "([^"]*)" of user "([^"]*)" is shared with group "([^"]*)"( with permissions ([\d]*))?$/
Joas Schilling's avatar
Joas Schilling committed
359 360 361 362
	 *
	 * @param string $filepath
	 * @param string $user
	 * @param string $group
363
	 */
364
	public function assureFileIsSharedWithGroup($entry, $filepath, $user, $group, $withPerms = null, $permissions = null){
365 366 367 368 369 370 371 372 373
		$fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares" . "?path=$filepath";
		$client = new Client();
		$options = [];
		if ($user === 'admin') {
			$options['auth'] = $this->adminUser;
		} else {
			$options['auth'] = [$user, $this->regularUser];
		}
		$this->response = $client->get($fullUrl, $options);
374
		if ($this->isUserOrGroupInSharedData($group, $permissions)){
375 376
			return;
		} else {
377
			$this->createShare($user, $filepath, 1, $group, null, null, $permissions);
378 379
		}
		$this->response = $client->get($fullUrl, $options);
380
		PHPUnit_Framework_Assert::assertEquals(True, $this->isUserOrGroupInSharedData($group, $permissions));
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
	}

	/**
	 * @When /^Deleting last share$/
	 */
	public function deletingLastShare(){
		$share_id = $this->lastShareData->data[0]->id;
		$url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
		$this->sendingToWith("DELETE", $url, null);
	}

	/**
	 * @When /^Getting info of last share$/
	 */
	public function gettingInfoOfLastShare(){
		$share_id = $this->lastShareData->data[0]->id;
		$url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
		$this->sendingToWith("GET", $url, null);
	}

	/**
	 * @Then /^last share_id is included in the answer$/
	 */
	public function checkingLastShareIDIsIncluded(){
		$share_id = $this->lastShareData->data[0]->id;
		if (!$this->isFieldInResponse('id', $share_id)){
			PHPUnit_Framework_Assert::fail("Share id $share_id not found in response");
		}
	}

	/**
	 * @Then /^last share_id is not included in the answer$/
	 */
	public function checkingLastShareIDIsNotIncluded(){
		$share_id = $this->lastShareData->data[0]->id;
		if ($this->isFieldInResponse('id', $share_id)){
			PHPUnit_Framework_Assert::fail("Share id $share_id has been found in response");
		}
	}

421 422 423 424 425 426 427 428
	/**
	 * @Then /^the response contains ([0-9]+) entries$/
	 */
	public function checkingTheResponseEntriesCount($count){
		$actualCount = count($this->response->xml()->data[0]);
		PHPUnit_Framework_Assert::assertEquals($count, $actualCount);
	}

429 430
	/**
	 * @Then /^Share fields of last share match with$/
Joas Schilling's avatar
Joas Schilling committed
431
	 * @param \Behat\Gherkin\Node\TableNode|null $body
432 433 434 435 436 437
	 */
	public function checkShareFields($body){
		if ($body instanceof \Behat\Gherkin\Node\TableNode) {
			$fd = $body->getRowsHash();

			foreach($fd as $field => $value) {
438 439 440 441 442 443 444 445
				if (substr($field, 0, 10 ) === "share_with"){
					$value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -5), $value);
					$value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -5), $value);
				}
				if (substr($field, 0, 6 ) === "remote"){
					$value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -4), $value);
					$value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -4), $value);
				}
446 447 448 449 450 451 452
				if (!$this->isFieldInResponse($field, $value)){
					PHPUnit_Framework_Assert::fail("$field" . " doesn't have value " . "$value");
				}
			}
		}
	}

453 454 455 456
	/**
	 * @Then As :user remove all shares from the file named :fileName
	 */
	public function asRemoveAllSharesFromTheFileNamed($user, $fileName) {
Joas Schilling's avatar
Joas Schilling committed
457
		$url = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares?format=json";
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
		$client = new \GuzzleHttp\Client();
		$res = $client->get(
			$url,
			[
				'auth' => [
					$user,
					'123456',
				],
				'headers' => [
					'Content-Type' => 'application/json',
				],
			]
		);
		$json = json_decode($res->getBody()->getContents(), true);
		$deleted = false;
		foreach($json['ocs']['data'] as $data) {
			if (stripslashes($data['path']) === $fileName) {
				$id = $data['id'];
				$client->delete(
Joas Schilling's avatar
Joas Schilling committed
477
					$this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/{$id}",
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
					[
						'auth' => [
							$user,
							'123456',
						],
						'headers' => [
							'Content-Type' => 'application/json',
						],
					]
				);
				$deleted = true;
			}
		}

		if($deleted === false) {
			throw new \Exception("Could not delete file $fileName");
		}
	}

Roeland Jago Douma's avatar
Roeland Jago Douma committed
497 498 499 500 501 502 503 504 505 506 507 508 509 510
	/**
	 * @When save last share id
	 */
	public function saveLastShareId()
	{
		$this->savedShareId = $this->lastShareData['data']['id'];
	}

	/**
	 * @Then share ids should match
	 */
	public function shareIdsShouldMatch()
	{
		if ($this->savedShareId !== $this->lastShareData['data']['id']) {
Joas Schilling's avatar
Joas Schilling committed
511
			throw new \Exception('Expected the same link share to be returned');
Roeland Jago Douma's avatar
Roeland Jago Douma committed
512 513
		}
	}
514

515 516
	/* Returns shares of a file or folders as an array of elements */
	public function getShares($user, $path) {
517 518 519 520 521 522 523 524 525 526 527 528 529
		$fullUrl = $this->baseUrl . "v{$this->apiVersion}.php/apps/files_sharing/api/v{$this->sharingApiVersion}/shares";
		$fullUrl = $fullUrl . '?path=' . $path;

		$client = new Client();
		$options = [];

		if ($user === 'admin') {
			$options['auth'] = $this->adminUser;
		} else {
			$options['auth'] = [$user, $this->regularUser];
		}

		$this->response = $client->send($client->createRequest("GET", $fullUrl, $options));
530 531 532 533 534 535 536 537 538 539 540 541
		return $this->response->xml()->data->element;
	}

	/**
	 * @When /^user "([^"]*)" checks public shares of (file|folder) "([^"]*)"$/
	 * @param string $user
	 * @param string $type
	 * @param string $path
	 * @param \Behat\Gherkin\Node\TableNode|null $body
	 */
	public function checkPublicShares($user, $type, $path, $TableNode){
		$dataResponded = $this->getShares($user, $path);
542 543 544

		if ($TableNode instanceof \Behat\Gherkin\Node\TableNode) {
			$elementRows = $TableNode->getRows();
545 546 547 548 549 550 551

			if ($elementRows[0][0] === '') {
				//It shouldn't have public shares
				PHPUnit_Framework_Assert::assertEquals(count($dataResponded), 0);
				return 0;
			}

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
			foreach($elementRows as $expectedElementsArray) {
				//0 path, 1 permissions, 2 name
				$nameFound = false;
				foreach ($dataResponded as $elementResponded) {
					if ((string)$elementResponded->name[0] === $expectedElementsArray[2]) {
						PHPUnit_Framework_Assert::assertEquals($expectedElementsArray[0], (string)$elementResponded->path[0]);
						PHPUnit_Framework_Assert::assertEquals($expectedElementsArray[1], (string)$elementResponded->permissions[0]);
						$nameFound = true;
						break;
					}
				}
				PHPUnit_Framework_Assert::assertTrue($nameFound, "Shared link name " . $expectedElementsArray[2] . " not found");
			}
		}
	}

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
	public function getPublicShareIDByName($user, $path, $name) {
		$dataResponded = $this->getShares($user, $path);
		foreach ($dataResponded as $elementResponded) {
			if ((string)$elementResponded->name[0] === $name){
				return (int)$elementResponded->id[0];
			}
		}
		return null;
	}

	/**
	 * @When /^user "([^"]*)" deletes public share named "([^"]*)" in (file|folder) "([^"]*)"$/
	 * @param string $user
	 * @param string $name
	 * @param string $type
	 * @param string $path
	 */
	public function deletingPublicShareNamed($user, $name, $type, $path){
		$share_id = $this->getPublicShareIDByName($user, $path, $name);
		$url = "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares/$share_id";
		$this->sendingToWith("DELETE", $url, null);
	}

591 592
}