Passed
Push — master ( e0d767...d0a7f8 )
by Roeland
24:12 queued 10:57
created

OwnershipTransferService::collectUsersShares()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 41
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 27
nc 3
nop 4
dl 0
loc 41
rs 8.5546
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @copyright 2019 Christoph Wurst <[email protected]>
7
 *
8
 * @author Christoph Wurst <[email protected]>
9
 * @author Joas Schilling <[email protected]>
10
 * @author Morris Jobke <[email protected]>
11
 * @author rawtaz <[email protected]>
12
 * @author Roeland Jago Douma <[email protected]>
13
 * @author Sascha Wiswedel <[email protected]>
14
 * @author Tobia De Koninck <[email protected]>
15
 *
16
 * @license GNU AGPL version 3 or any later version
17
 *
18
 * This program is free software: you can redistribute it and/or modify
19
 * it under the terms of the GNU Affero General Public License as
20
 * published by the Free Software Foundation, either version 3 of the
21
 * License, or (at your option) any later version.
22
 *
23
 * This program is distributed in the hope that it will be useful,
24
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26
 * GNU Affero General Public License for more details.
27
 *
28
 * You should have received a copy of the GNU Affero General Public License
29
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30
 *
31
 */
32
33
namespace OCA\Files\Service;
34
35
use Closure;
36
use OC\Files\Filesystem;
37
use OC\Files\View;
38
use OCA\Files\Exception\TransferOwnershipException;
39
use OCP\Encryption\IManager as IEncryptionManager;
40
use OCP\Files\Config\IUserMountCache;
41
use OCP\Files\FileInfo;
42
use OCP\Files\IHomeStorage;
43
use OCP\Files\InvalidPathException;
44
use OCP\Files\Mount\IMountManager;
45
use OCP\IUser;
46
use OCP\Share\IManager as IShareManager;
47
use OCP\Share\IShare;
48
use Symfony\Component\Console\Helper\ProgressBar;
49
use Symfony\Component\Console\Output\NullOutput;
50
use Symfony\Component\Console\Output\OutputInterface;
51
use function array_merge;
52
use function basename;
53
use function count;
54
use function date;
55
use function is_dir;
56
use function rtrim;
57
58
class OwnershipTransferService {
59
60
	/** @var IEncryptionManager */
61
	private $encryptionManager;
62
63
	/** @var IShareManager */
64
	private $shareManager;
65
66
	/** @var IMountManager */
67
	private $mountManager;
68
69
	/** @var IUserMountCache */
70
	private $userMountCache;
71
72
	public function __construct(IEncryptionManager $manager,
73
								IShareManager $shareManager,
74
								IMountManager $mountManager,
75
								IUserMountCache $userMountCache) {
76
		$this->encryptionManager = $manager;
77
		$this->shareManager = $shareManager;
78
		$this->mountManager = $mountManager;
79
		$this->userMountCache = $userMountCache;
80
	}
81
82
	/**
83
	 * @param IUser $sourceUser
84
	 * @param IUser $destinationUser
85
	 * @param string $path
86
	 *
87
	 * @param OutputInterface|null $output
88
	 * @param bool $move
89
	 * @throws TransferOwnershipException
90
	 * @throws \OC\User\NoUserException
91
	 */
92
	public function transfer(IUser $sourceUser,
93
							 IUser $destinationUser,
94
							 string $path,
95
							 ?OutputInterface $output = null,
96
							 bool $move = false,
97
							 bool $firstLogin = false): void {
98
		$output = $output ?? new NullOutput();
99
		$sourceUid = $sourceUser->getUID();
100
		$destinationUid = $destinationUser->getUID();
101
		$sourcePath = rtrim($sourceUid . '/files/' . $path, '/');
102
103
		// target user has to be ready
104
		if ($destinationUser->getLastLogin() === 0 || !$this->encryptionManager->isReadyForUser($destinationUid)) {
0 ignored issues
show
Bug introduced by
The method isReadyForUser() does not exist on OCP\Encryption\IManager. Since it exists in all sub-types, consider adding an abstract or default implementation to OCP\Encryption\IManager. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

104
		if ($destinationUser->getLastLogin() === 0 || !$this->encryptionManager->/** @scrutinizer ignore-call */ isReadyForUser($destinationUid)) {
Loading history...
105
			throw new TransferOwnershipException("The target user is not ready to accept files. The user has at least to have logged in once.", 2);
106
		}
107
108
		// setup filesystem
109
		Filesystem::initMountPoints($sourceUid);
110
		Filesystem::initMountPoints($destinationUid);
111
112
		$view = new View();
113
114
		if ($move) {
115
			$finalTarget = "$destinationUid/files/";
116
		} else {
117
			$date = date('Y-m-d H-i-s');
118
119
			// Remove some characters which are prone to cause errors
120
			$cleanUserName = str_replace(['\\', '/', ':', '.', '?', '#', '\'', '"'], '-', $sourceUser->getDisplayName());
121
			// Replace multiple dashes with one dash
122
			$cleanUserName = preg_replace('/-{2,}/s', '-', $cleanUserName);
123
			$cleanUserName = $cleanUserName ?: $sourceUid;
124
125
			$finalTarget = "$destinationUid/files/transferred from $cleanUserName on $date";
126
			try {
127
				$view->verifyPath(dirname($finalTarget), basename($finalTarget));
128
			} catch (InvalidPathException $e) {
129
				$finalTarget = "$destinationUid/files/transferred from $sourceUid on $date";
130
			}
131
		}
132
133
		if (!($view->is_dir($sourcePath) || $view->is_file($sourcePath))) {
134
			throw new TransferOwnershipException("Unknown path provided: $path", 1);
135
		}
136
137
		if ($move && (
138
				!$view->is_dir($finalTarget) || (
139
					!$firstLogin &&
140
					count($view->getDirectoryContent($finalTarget)) > 0
141
				)
142
			)
143
		) {
144
			throw new TransferOwnershipException("Destination path does not exists or is not empty", 1);
145
		}
146
147
148
		// analyse source folder
149
		$this->analyse(
150
			$sourceUid,
151
			$destinationUid,
152
			$sourcePath,
153
			$view,
154
			$output
155
		);
156
157
		// collect all the shares
158
		$shares = $this->collectUsersShares(
159
			$sourceUid,
160
			$output,
161
			$view,
162
			$sourcePath
163
		);
164
165
		// transfer the files
166
		$this->transferFiles(
167
			$sourceUid,
168
			$sourcePath,
169
			$finalTarget,
170
			$view,
171
			$output
172
		);
173
174
		// restore the shares
175
		$this->restoreShares(
176
			$sourceUid,
177
			$destinationUid,
178
			$shares,
179
			$output
180
		);
181
	}
182
183
	private function walkFiles(View $view, $path, Closure $callBack) {
184
		foreach ($view->getDirectoryContent($path) as $fileInfo) {
185
			if (!$callBack($fileInfo)) {
186
				return;
187
			}
188
			if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
189
				$this->walkFiles($view, $fileInfo->getPath(), $callBack);
190
			}
191
		}
192
	}
193
194
	/**
195
	 * @param OutputInterface $output
196
	 *
197
	 * @throws \Exception
198
	 */
199
	protected function analyse(string $sourceUid,
200
							   string $destinationUid,
201
							   string $sourcePath,
202
							   View $view,
203
							   OutputInterface $output): void {
204
		$output->writeln('Validating quota');
205
		$size = $view->getFileInfo($sourcePath, false)->getSize(false);
206
		$freeSpace = $view->free_space($destinationUid . '/files/');
207
		if ($size > $freeSpace && $freeSpace !== FileInfo::SPACE_UNKNOWN) {
208
			$output->writeln('<error>Target user does not have enough free space available.</error>');
209
			throw new \Exception('Execution terminated.');
210
		}
211
212
		$output->writeln("Analysing files of $sourceUid ...");
213
		$progress = new ProgressBar($output);
214
		$progress->start();
215
216
		$encryptedFiles = [];
217
		$this->walkFiles($view, $sourcePath,
218
			function (FileInfo $fileInfo) use ($progress) {
219
				if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
220
					// only analyze into folders from main storage,
221
					if (!$fileInfo->getStorage()->instanceOfStorage(IHomeStorage::class)) {
222
						return false;
223
					}
224
					return true;
225
				}
226
				$progress->advance();
227
				if ($fileInfo->isEncrypted()) {
228
					$encryptedFiles[] = $fileInfo;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$encryptedFiles was never initialized. Although not strictly required by PHP, it is generally a good practice to add $encryptedFiles = array(); before regardless.
Loading history...
229
				}
230
				return true;
231
			});
232
		$progress->finish();
233
		$output->writeln('');
234
235
		// no file is allowed to be encrypted
236
		if (!empty($encryptedFiles)) {
237
			$output->writeln("<error>Some files are encrypted - please decrypt them first.</error>");
238
			foreach ($encryptedFiles as $encryptedFile) {
239
				/** @var FileInfo $encryptedFile */
240
				$output->writeln("  " . $encryptedFile->getPath());
241
			}
242
			throw new \Exception('Execution terminated.');
243
		}
244
	}
245
246
	private function collectUsersShares(string $sourceUid,
247
										OutputInterface $output,
248
										View $view,
249
										?string $path = null): array {
250
		$output->writeln("Collecting all share information for files and folders of $sourceUid ...");
251
252
		$shares = [];
253
		$progress = new ProgressBar($output);
254
		foreach ([IShare::TYPE_GROUP, IShare::TYPE_USER, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_ROOM, IShare::TYPE_EMAIL, IShare::TYPE_CIRCLE] as $shareType) {
255
			$offset = 0;
256
			while (true) {
257
				$sharePage = $this->shareManager->getSharesBy($sourceUid, $shareType, null, true, 50, $offset);
258
				$progress->advance(count($sharePage));
259
				if (empty($sharePage)) {
260
					break;
261
				}
262
				if ($path !== null) {
263
					$sharePage = array_filter($sharePage, function (IShare $share) use ($view, $path) {
264
						try {
265
							$relativePath = $view->getPath($share->getNodeId());
266
							$singleFileTranfer = $view->is_file($path);
267
							if ($singleFileTranfer) {
268
								return Filesystem::normalizePath($relativePath) === Filesystem::normalizePath($path);
269
							}
270
271
							return mb_strpos(
272
								Filesystem::normalizePath($relativePath . '/', false),
273
								Filesystem::normalizePath($path . '/', false)) === 0;
274
						} catch (\Exception $e) {
275
							return false;
276
						}
277
					});
278
				}
279
				$shares = array_merge($shares, $sharePage);
280
				$offset += 50;
281
			}
282
		}
283
284
		$progress->finish();
285
		$output->writeln('');
286
		return $shares;
287
	}
288
289
	/**
290
	 * @throws TransferOwnershipException
291
	 */
292
	protected function transferFiles(string $sourceUid,
293
									 string $sourcePath,
294
									 string $finalTarget,
295
									 View $view,
296
									 OutputInterface $output): void {
297
		$output->writeln("Transferring files to $finalTarget ...");
298
299
		// This change will help user to transfer the folder specified using --path option.
300
		// Else only the content inside folder is transferred which is not correct.
301
		if ($sourcePath !== "$sourceUid/files") {
302
			$view->mkdir($finalTarget);
303
			$finalTarget = $finalTarget . '/' . basename($sourcePath);
304
		}
305
		if ($view->rename($sourcePath, $finalTarget) === false) {
306
			throw new TransferOwnershipException("Could not transfer files.", 1);
307
		}
308
		if (!is_dir("$sourceUid/files")) {
309
			// because the files folder is moved away we need to recreate it
310
			$view->mkdir("$sourceUid/files");
311
		}
312
	}
313
314
	private function restoreShares(string $sourceUid,
315
								   string $destinationUid,
316
								   array $shares,
317
								   OutputInterface $output) {
318
		$output->writeln("Restoring shares ...");
319
		$progress = new ProgressBar($output, count($shares));
320
321
		foreach ($shares as $share) {
322
			try {
323
				if ($share->getShareType() === IShare::TYPE_USER &&
324
					$share->getSharedWith() === $destinationUid) {
325
					// Unmount the shares before deleting, so we don't try to get the storage later on.
326
					$shareMountPoint = $this->mountManager->find('/' . $destinationUid . '/files' . $share->getTarget());
327
					if ($shareMountPoint) {
328
						$this->mountManager->removeMount($shareMountPoint->getMountPoint());
329
					}
330
					$this->shareManager->deleteShare($share);
331
				} else {
332
					if ($share->getShareOwner() === $sourceUid) {
333
						$share->setShareOwner($destinationUid);
334
					}
335
					if ($share->getSharedBy() === $sourceUid) {
336
						$share->setSharedBy($destinationUid);
337
					}
338
339
340
					// trigger refetching of the node so that the new owner and mountpoint are taken into account
341
					// otherwise the checks on the share update will fail due to the original node not being available in the new user scope
342
					$this->userMountCache->clear();
343
					$share->setNodeId($share->getNode()->getId());
344
345
					$this->shareManager->updateShare($share);
346
				}
347
			} catch (\OCP\Files\NotFoundException $e) {
348
				$output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted file, skipping</error>');
349
			} catch (\Throwable $e) {
350
				$output->writeln('<error>Could not restore share with id ' . $share->getId() . ':' . $e->getTraceAsString() . '</error>');
351
			}
352
			$progress->advance();
353
		}
354
		$progress->finish();
355
		$output->writeln('');
356
	}
357
}
358