/* * Copyright 2011 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.utils; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; /** * Common file utilities. * * @author James Moger * */ public class FileUtils { /** 1024 (number of bytes in one kilobyte) */ public static final int KB = 1024; /** 1024 {@link #KB} (number of bytes in one megabyte) */ public static final int MB = 1024 * KB; /** 1024 {@link #MB} (number of bytes in one gigabyte) */ public static final int GB = 1024 * MB; /** * Returns an int from a string representation of a file size. * e.g. 50m = 50 megabytes * * @param aString * @param defaultValue * @return an int value or the defaultValue if aString can not be parsed */ public static int convertSizeToInt(String aString, int defaultValue) { return (int) convertSizeToLong(aString, defaultValue); } /** * Returns a long from a string representation of a file size. * e.g. 50m = 50 megabytes * * @param aString * @param defaultValue * @return a long value or the defaultValue if aString can not be parsed */ public static long convertSizeToLong(String aString, long defaultValue) { // trim string and remove all spaces aString = aString.toLowerCase().trim(); StringBuilder sb = new StringBuilder(); for (String a : aString.split(" ")) { sb.append(a); } aString = sb.toString(); // identify value and unit int idx = 0; int len = aString.length(); while (Character.isDigit(aString.charAt(idx))) { idx++; if (idx == len) { break; } } long value = 0; String unit = null; try { value = Long.parseLong(aString.substring(0, idx)); unit = aString.substring(idx); } catch (Exception e) { return defaultValue; } if (unit.equals("g") || unit.equals("gb")) { return value * GB; } else if (unit.equals("m") || unit.equals("mb")) { return value * MB; } else if (unit.equals("k") || unit.equals("kb")) { return value * KB; } return defaultValue; } /** * Returns the byte [] content of the specified file. * * @param file * @return the byte content of the file */ public static byte [] readContent(File file) { byte [] buffer = new byte[(int) file.length()]; BufferedInputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); is.read(buffer, 0, buffer.length); } catch (Throwable t) { System.err.println("Failed to read byte content of " + file.getAbsolutePath()); t.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { System.err.println("Failed to close file " + file.getAbsolutePath()); ioe.printStackTrace(); } } } return buffer; } /** * Returns the string content of the specified file. * * @param file * @param lineEnding * @return the string content of the file */ public static String readContent(File file, String lineEnding) { StringBuilder sb = new StringBuilder(); InputStreamReader is = null; BufferedReader reader = null; try { is = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); if (lineEnding != null) { sb.append(lineEnding); } } } catch (Throwable t) { System.err.println("Failed to read content of " + file.getAbsolutePath()); t.printStackTrace(); } finally { if (reader != null){ try { reader.close(); } catch (IOException ioe) { System.err.println("Failed to close file " + file.getAbsolutePath()); ioe.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException ioe) { System.err.println("Failed to close file " + file.getAbsolutePath()); ioe.printStackTrace(); } } } return sb.toString(); } /** * Writes the string content to the file. * * @param file * @param content */ public static void writeContent(File file, String content) { OutputStreamWriter os = null; try { os = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")); BufferedWriter writer = new BufferedWriter(os); writer.append(content); writer.flush(); } catch (Throwable t) { System.err.println("Failed to write content of " + file.getAbsolutePath()); t.printStackTrace(); } finally { if (os != null) { try { os.close(); } catch (IOException ioe) { System.err.println("Failed to close file " + file.getAbsolutePath()); ioe.printStackTrace(); } } } } /** * Recursively traverses a folder and its subfolders to calculate the total * size in bytes. * * @param directory * @return folder size in bytes */ public static long folderSize(File directory) { if (directory == null || !directory.exists()) { return -1; } if (directory.isDirectory()) { long length = 0; for (File file : directory.listFiles()) { length += folderSize(file); } return length; } else if (directory.isFile()) { return directory.length(); } return 0; } /** * Delete a file or recursively delete a folder. * * @param fileOrFolder * @return true, if successful */ public static boolean delete(File fileOrFolder) { boolean success = false; if (fileOrFolder.isDirectory()) { File [] files = fileOrFolder.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { success |= delete(file); } else { success |= file.delete(); } } } } success |= fileOrFolder.delete(); return success; } /** * Copies a file or folder (recursively) to a destination folder. * * @param destinationFolder * @param filesOrFolders * @return * @throws FileNotFoundException * @throws IOException */ public static void copy(File destinationFolder, File... filesOrFolders) throws FileNotFoundException, IOException { destinationFolder.mkdirs(); for (File file : filesOrFolders) { if (file.isDirectory()) { copy(new File(destinationFolder, file.getName()), file.listFiles()); } else { File dFile = new File(destinationFolder, file.getName()); BufferedInputStream bufin = null; FileOutputStream fos = null; try { bufin = new BufferedInputStream(new FileInputStream(file)); fos = new FileOutputStream(dFile); int len = 8196; byte[] buff = new byte[len]; int n = 0; while ((n = bufin.read(buff, 0, len)) != -1) { fos.write(buff, 0, n); } } finally { try { if (bufin != null) bufin.close(); } catch (Throwable t) { } try { if (fos != null) fos.close(); } catch (Throwable t) { } } dFile.setLastModified(file.lastModified()); } } } /** * Determine the relative path between two files. Takes into account * canonical paths, if possible. * * @param basePath * @param path * @return a relative path from basePath to path */ public static String getRelativePath(File basePath, File path) { Path exactBase = Paths.get(getExactFile(basePath).toURI()); Path exactPath = Paths.get(getExactFile(path).toURI()); if (exactPath.startsWith(exactBase)) { return exactBase.relativize(exactPath).toString().replace('\\', '/'); } // no relative relationship return null; } /** * Returns the exact path for a file. This path will be the canonical path * unless an exception is thrown in which case it will be the absolute path. * * @param path * @return the exact file */ public static File getExactFile(File path) { try { return path.getCanonicalFile(); } catch (IOException e) { return path.getAbsoluteFile(); } } public static File resolveParameter(String parameter, File aFolder, String path) { if (aFolder == null) { // strip any parameter reference path = path.replace(parameter, "").trim(); if (path.length() > 0 && path.charAt(0) == '/') { // strip leading / path = path.substring(1); } } else if (path.contains(parameter)) { // replace parameter with path path = path.replace(parameter, aFolder.getAbsolutePath()); } return new File(path); } } _disabled_users_search Nextcloud server, a safe home for all your data: https://github.com/nextcloud/serverwww-data
aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php
blob: bf02e8114df89006ee969d1cde8c82781b68af67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
177
178
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
207
208
209
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php
/**
 * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
 * SPDX-License-Identifier: AGPL-3.0-only
 */
namespace OCA\Files_Sharing\Tests\Controller;

use OCA\Files_Sharing\Controller\ShareesAPIController;
use OCA\Files_Sharing\Tests\TestCase;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\Collaboration\Collaborators\ISearch;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\Share\IManager;
use OCP\Share\IShare;
use PHPUnit\Framework\MockObject\MockObject;

/**
 * Class ShareesTest
 *
 * @group DB
 *
 * @package OCA\Files_Sharing\Tests\API
 */
class ShareesAPIControllerTest extends TestCase {
	/** @var ShareesAPIController */
	protected $sharees;

	/** @var string */
	protected $uid;

	/** @var IRequest|MockObject */
	protected $request;

	/** @var IManager|MockObject */
	protected $shareManager;

	/** @var ISearch|MockObject */
	protected $collaboratorSearch;

	/** @var IConfig|MockObject */
	protected $config;

	protected function setUp(): void {
		parent::setUp();

		$this->uid = 'test123';
		$this->request = $this->createMock(IRequest::class);
		$this->shareManager = $this->createMock(IManager::class);
		$this->config = $this->createMock(IConfig::class);

		/** @var IURLGenerator|MockObject $urlGeneratorMock */
		$urlGeneratorMock = $this->createMock(IURLGenerator::class);

		$this->collaboratorSearch = $this->createMock(ISearch::class);

		$this->sharees = new ShareesAPIController(
			'files_sharing',
			$this->request,
			$this->uid,
			$this->config,
			$urlGeneratorMock,
			$this->shareManager,
			$this->collaboratorSearch
		);
	}

	public function dataSearch(): array {
		$noRemote = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_EMAIL];
		$allTypes = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_REMOTE, IShare::TYPE_REMOTE_GROUP, IShare::TYPE_EMAIL];

		return [
			[[], '', 'yes', false, true, true, true, $noRemote, false, true, true],

			// Test itemType
			[[
				'search' => '',
			], '', 'yes', false, true, true, true, $noRemote, false, true, true],
			[[
				'search' => 'foobar',
			], '', 'yes', false, true, true, true, $noRemote, false, true, true],
			[[
				'search' => 0,
			], '', 'yes', false, true, true, true, $noRemote, false, true, true],

			// Test itemType
			[[
				'itemType' => '',
			], '', 'yes', false, true, true, true, $noRemote, false, true, true],
			[[
				'itemType' => 'folder',
			], '', 'yes', false, true, true, true, $allTypes, false, true, true],
			[[
				'itemType' => 0,
			], '', 'yes', false, true, true , true, $noRemote, false, true, true],
			// Test shareType
			[[
				'itemType' => 'call',
			], '', 'yes', false, true, true, true, $noRemote, false, true, true],
			[[
				'itemType' => 'call',
			], '', 'yes', false, true, true, true, [0, 4], false, true, false],
			[[
				'itemType' => 'folder',
			], '', 'yes', false, true, true, true, $allTypes, false, true, true],
			[[
				'itemType' => 'folder',
				'shareType' => 0,
			], '', 'yes', false, true, true, false, [0], false, true, true],
			[[
				'itemType' => 'folder',
				'shareType' => '0',
			], '', 'yes', false, true, true, false, [0], false, true, true],
			[[
				'itemType' => 'folder',
				'shareType' => 1,
			], '', 'yes', false, true, true, false, [1], false, true, true],
			[[
				'itemType' => 'folder',
				'shareType' => 12,
			], '', 'yes', false, true, true, false, [], false, true, true],
			[[
				'itemType' => 'folder',
				'shareType' => 'foobar',
			], '', 'yes', false, true, true, true, $allTypes, false, true, true],

			[[
				'itemType' => 'folder',
				'shareType' => [0, 1, 2],
			], '', 'yes', false, false, false, false, [0, 1], false, true, true],
			[[
				'itemType' => 'folder',
				'shareType' => [0, 1],
			], '', 'yes', false, false, false, false, [0, 1], false, true, true],
			[[
				'itemType' => 'folder',
				'shareType' => $allTypes,
			], '', 'yes', false, true, true, true, $allTypes, false, true, true],
			[[
				'itemType' => 'folder',
				'shareType' => $allTypes,
			], '', 'yes', false, false, false, false, [0, 1], false, true, true],
			[[
				'itemType' => 'folder',
				'shareType' => $allTypes,
			], '', 'yes', false, true, false, false, [0, 6], false, true, false],
			[[
				'itemType' => 'folder',
				'shareType' => $allTypes,
			], '', 'yes', false, false, false, true, [0, 4], false, true, false],
			[[
				'itemType' => 'folder',
				'shareType' => $allTypes,
			], '', 'yes', false, true, true, false, [0, 6, 9], false, true, false],

			// Test pagination
			[[
				'itemType' => 'folder',
				'page' => 1,
			], '', 'yes', false, true, true, true, $allTypes, false, true, true],
			[[
				'itemType' => 'folder',
				'page' => 10,
			], '', 'yes', false, true, true, true, $allTypes, false, true, true],

			// Test perPage
			[[
				'itemType' => 'folder',
				'perPage' => 1,
			], '', 'yes', false, true, true, true, $allTypes, false, true, true],
			[[
				'itemType' => 'folder',
				'perPage' => 10,
			], '', 'yes', false, true, true, true, $allTypes, false, true, true],

			// Test $shareWithGroupOnly setting
			[[
				'itemType' => 'folder',
			], 'no', 'yes', false, true, true, true, $allTypes, false, true, true],
			[[
				'itemType' => 'folder',
			], 'yes', 'yes', false, true, true, true, $allTypes, true, true, true],

			// Test $shareeEnumeration setting
			[[
				'itemType' => 'folder',
			], 'no', 'yes', false, true, true, true, $allTypes, false, true, true],
			[[
				'itemType' => 'folder',
			], 'no', 'no', false, true, true, true, $allTypes, false, false, true],

		];
	}

	/**
	 * @dataProvider dataSearch
	 *
	 * @param array $getData
	 * @param string $apiSetting
	 * @param string $enumSetting
	 * @param bool $remoteSharingEnabled
	 * @param bool $isRemoteGroupSharingEnabled
	 * @param bool $emailSharingEnabled
	 * @param array $shareTypes
	 * @param bool $shareWithGroupOnly
	 * @param bool $shareeEnumeration
	 * @param bool $allowGroupSharing
	 * @throws OCSBadRequestException
	 */
	public function testSearch(
		array $getData,
		string $apiSetting,
		string $enumSetting,
		bool $sharingDisabledForUser,
		bool $remoteSharingEnabled,
		bool $isRemoteGroupSharingEnabled,
		bool $emailSharingEnabled,
		array $shareTypes,
		bool $shareWithGroupOnly,
		bool $shareeEnumeration,
		bool $allowGroupSharing,
	): void {
		$search = $getData['search'] ?? '';
		$itemType = $getData['itemType'] ?? 'irrelevant';
		$page = $getData['page'] ?? 1;
		$perPage = $getData['perPage'] ?? 200;
		$shareType = $getData['shareType'] ?? null;

		/** @var IConfig|MockObject $config */
		$config = $this->createMock(IConfig::class);
		$config->expects($this->exactly(1))
			->method('getAppValue')
			->with($this->anything(), $this->anything(), $this->anything())
			->willReturnMap([
				['files_sharing', 'lookupServerEnabled', 'yes', 'yes'],
			]);

		$this->shareManager->expects($this->once())
			->method('allowGroupSharing')
			->willReturn($allowGroupSharing);

		/** @var string */
		$uid = 'test123';
		/** @var IRequest|MockObject $request */
		$request = $this->createMock(IRequest::class);
		/** @var IURLGenerator|MockObject $urlGenerator */
		$urlGenerator = $this->createMock(IURLGenerator::class);

		/** @var MockObject|ShareesAPIController $sharees */
		$sharees = $this->getMockBuilder(ShareesAPIController::class)
			->setConstructorArgs([
				'files_sharing',
				$request,
				$uid,
				$config,
				$urlGenerator,
				$this->shareManager,
				$this->collaboratorSearch
			])
			->onlyMethods(['isRemoteSharingAllowed', 'isRemoteGroupSharingAllowed'])
			->getMock();

		$expectedShareTypes = $shareTypes;
		sort($expectedShareTypes);

		$this->collaboratorSearch->expects($this->once())
			->method('search')
			->with($search, $expectedShareTypes, $this->anything(), $perPage, $perPage * ($page - 1))
			->willReturn([[], false]);

		$sharees->expects($this->any())
			->method('isRemoteSharingAllowed')
			->with($itemType)
			->willReturn($remoteSharingEnabled);


		$sharees->expects($this->any())
			->method('isRemoteGroupSharingAllowed')
			->with($itemType)
			->willReturn($isRemoteGroupSharingEnabled);

		$this->shareManager->expects($this->any())
			->method('sharingDisabledForUser')
			->with($uid)
			->willReturn($sharingDisabledForUser);

		$this->shareManager->expects($this->any())
			->method('shareProviderExists')
			->willReturnCallback(function ($shareType) use ($emailSharingEnabled) {
				if ($shareType === IShare::TYPE_EMAIL) {
					return $emailSharingEnabled;
				} else {
					return false;
				}
			});

		$this->assertInstanceOf(Http\DataResponse::class, $sharees->search($search, $itemType, $page, $perPage, $shareType));
	}

	public function dataSearchInvalid(): array {
		return [
			// Test invalid pagination
			[[
				'page' => 0,
			], 'Invalid page'],
			[[
				'page' => '0',
			], 'Invalid page'],
			[[
				'page' => -1,
			], 'Invalid page'],

			// Test invalid perPage
			[[
				'perPage' => 0,
			], 'Invalid perPage argument'],
			[[
				'perPage' => '0',
			], 'Invalid perPage argument'],
			[[
				'perPage' => -1,
			], 'Invalid perPage argument'],
		];
	}

	/**
	 * @dataProvider dataSearchInvalid
	 *
	 * @param array $getData
	 * @param string $message
	 */
	public function testSearchInvalid($getData, $message): void {
		$page = $getData['page'] ?? 1;
		$perPage = $getData['perPage'] ?? 200;

		/** @var IConfig|MockObject $config */
		$config = $this->createMock(IConfig::class);
		$config->expects($this->never())
			->method('getAppValue');

		/** @var string */
		$uid = 'test123';
		/** @var IRequest|MockObject $request */
		$request = $this->createMock(IRequest::class);
		/** @var IURLGenerator|MockObject $urlGenerator */
		$urlGenerator = $this->createMock(IURLGenerator::class);

		/** @var MockObject|ShareesAPIController $sharees */
		$sharees = $this->getMockBuilder('\OCA\Files_Sharing\Controller\ShareesAPIController')
			->setConstructorArgs([
				'files_sharing',
				$request,
				$uid,
				$config,
				$urlGenerator,
				$this->shareManager,
				$this->collaboratorSearch
			])
			->onlyMethods(['isRemoteSharingAllowed'])
			->getMock();
		$sharees->expects($this->never())
			->method('isRemoteSharingAllowed');

		$this->collaboratorSearch->expects($this->never())
			->method('search');

		try {
			$sharees->search('', null, $page, $perPage, null);
			$this->fail();
		} catch (OCSBadRequestException $e) {
			$this->assertEquals($message, $e->getMessage());
		}
	}

	public function dataIsRemoteSharingAllowed() {
		return [
			['file', true],
			['folder', true],
			['', false],
			['contacts', false],
		];
	}

	/**
	 * @dataProvider dataIsRemoteSharingAllowed
	 *
	 * @param string $itemType
	 * @param bool $expected
	 */
	public function testIsRemoteSharingAllowed($itemType, $expected): void {
		$this->assertSame($expected, $this->invokePrivate($this->sharees, 'isRemoteSharingAllowed', [$itemType]));
	}

	public function testSearchSharingDisabled(): void {
		$this->shareManager->expects($this->once())
			->method('sharingDisabledForUser')
			->with($this->uid)
			->willReturn(true);

		$this->config->expects($this->once())
			->method('getSystemValueInt')
			->with('sharing.minSearchStringLength', 0)
			->willReturn(0);

		$this->shareManager->expects($this->never())
			->method('allowGroupSharing');

		$this->assertInstanceOf(DataResponse::class, $this->sharees->search('', null, 1, 10, [], false));
	}

	public function testSearchNoItemType(): void {
		$this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
		$this->expectExceptionMessage('Missing itemType');

		$this->sharees->search('', null, 1, 10, [], false);
	}

	public function dataGetPaginationLink() {
		return [
			[1, '/ocs/v1.php', ['perPage' => 2], '<?perPage=2&page=2>; rel="next"'],
			[10, '/ocs/v2.php', ['perPage' => 2], '<?perPage=2&page=11>; rel="next"'],
		];
	}

	/**
	 * @dataProvider dataGetPaginationLink
	 *
	 * @param int $page
	 * @param string $scriptName
	 * @param array $params
	 * @param array $expected
	 */
	public function testGetPaginationLink($page, $scriptName, $params, $expected): void {
		$this->request->expects($this->once())
			->method('getScriptName')
			->willReturn($scriptName);

		$this->assertEquals($expected, $this->invokePrivate($this->sharees, 'getPaginationLink', [$page, $params]));
	}

	public function dataIsV2() {
		return [
			['/ocs/v1.php', false],
			['/ocs/v2.php', true],
		];
	}

	/**
	 * @dataProvider dataIsV2
	 *
	 * @param string $scriptName
	 * @param bool $expected
	 */
	public function testIsV2($scriptName, $expected): void {
		$this->request->expects($this->once())
			->method('getScriptName')
			->willReturn($scriptName);

		$this->assertEquals($expected, $this->invokePrivate($this->sharees, 'isV2'));
	}
}