Completed
Push — master ( adb757...9d634f )
by Thomas
08:57
created

TransferOwnership   B

Complexity

Total Complexity 30

Size/Duplication

Total Lines 218
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
wmc 30
lcom 1
cbo 17
dl 0
loc 218
rs 7.8571
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A configure() 0 15 1
B execute() 0 40 4
A walkFiles() 0 10 4
C analyse() 0 37 7
A collectUsersShares() 0 20 4
A transfer() 0 7 1
C restoreShares() 0 33 8
1
<?php
2
/**
3
 * @author Carla Schroder <[email protected]>
4
 * @author Joas Schilling <[email protected]>
5
 * @author Thomas Müller <[email protected]>
6
 *
7
 * @copyright Copyright (c) 2016, ownCloud GmbH.
8
 * @license AGPL-3.0
9
 *
10
 * This code is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License, version 3,
12
 * as published by the Free Software Foundation.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License, version 3,
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
21
 *
22
 */
23
24
namespace OCA\Files\Command;
25
26
use OC\Files\Filesystem;
27
use OC\Files\View;
28
use OCP\Files\FileInfo;
29
use OCP\Files\Mount\IMountManager;
30
use OCP\IUserManager;
31
use OCP\Share\IManager;
32
use OCP\Share\IShare;
33
use Symfony\Component\Console\Command\Command;
34
use Symfony\Component\Console\Helper\ProgressBar;
35
use Symfony\Component\Console\Input\InputArgument;
36
use Symfony\Component\Console\Input\InputInterface;
37
use Symfony\Component\Console\Output\OutputInterface;
38
39
class TransferOwnership extends Command {
40
41
	/** @var IUserManager $userManager */
42
	private $userManager;
43
44
	/** @var IManager */
45
	private $shareManager;
46
47
	/** @var IMountManager */
48
	private $mountManager;
49
50
	/** @var FileInfo[] */
51
	private $allFiles = [];
52
53
	/** @var FileInfo[] */
54
	private $encryptedFiles = [];
55
56
	/** @var IShare[] */
57
	private $shares = [];
58
59
	/** @var string */
60
	private $sourceUser;
61
62
	/** @var string */
63
	private $destinationUser;
64
65
	/** @var string */
66
	private $finalTarget;
67
68
	public function __construct(IUserManager $userManager, IManager $shareManager, IMountManager $mountManager) {
69
		$this->userManager = $userManager;
70
		$this->shareManager = $shareManager;
71
		$this->mountManager = $mountManager;
72
		parent::__construct();
73
	}
74
75
	protected function configure() {
76
		$this
77
			->setName('files:transfer-ownership')
78
			->setDescription('All files and folders are moved to another user - shares are moved as well.')
79
			->addArgument(
80
				'source-user',
81
				InputArgument::REQUIRED,
82
				'owner of files which shall be moved'
83
			)
84
			->addArgument(
85
				'destination-user',
86
				InputArgument::REQUIRED,
87
				'user who will be the new owner of the files'
88
			);
89
	}
90
91
	protected function execute(InputInterface $input, OutputInterface $output) {
92
		$sourceUserObject = $this->userManager->get($input->getArgument('source-user'));
93
		$destinationUserObject = $this->userManager->get($input->getArgument('destination-user'));
94
		if (is_null($sourceUserObject)) {
95
			$output->writeln("<error>Unknown source user $this->sourceUser</error>");
96
			return 1;
97
		}
98
		if (is_null($destinationUserObject)) {
99
			$output->writeln("<error>Unknown destination user $this->destinationUser</error>");
100
			return 1;
101
		}
102
103
		$this->sourceUser = $sourceUserObject->getUID();
104
		$this->destinationUser = $destinationUserObject->getUID();
105
106
		// target user has to be ready
107
		if (!\OC::$server->getEncryptionManager()->isReadyForUser($this->destinationUser)) {
108
			$output->writeln("<error>The target user is not ready to accept files. The user has at least to be logged in once.</error>");
109
			return 2;
110
		}
111
112
		$date = date('c');
113
		$this->finalTarget = "$this->destinationUser/files/transferred from $this->sourceUser on $date";
114
115
		// setup filesystem
116
		Filesystem::initMountPoints($this->sourceUser);
117
		Filesystem::initMountPoints($this->destinationUser);
118
119
		// analyse source folder
120
		$this->analyse($output);
121
122
		// collect all the shares
123
		$this->collectUsersShares($output);
124
125
		// transfer the files
126
		$this->transfer($output);
127
128
		// restore the shares
129
		$this->restoreShares($output);
130
	}
131
132
	private function walkFiles(View $view, $path, \Closure $callBack) {
133
		foreach ($view->getDirectoryContent($path) as $fileInfo) {
134
			if (!$callBack($fileInfo)) {
135
				return;
136
			}
137
			if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
138
				$this->walkFiles($view, $fileInfo->getPath(), $callBack);
139
			}
140
		}
141
	}
142
143
	/**
144
	 * @param OutputInterface $output
145
	 * @throws \Exception
146
	 */
147
	protected function analyse(OutputInterface $output) {
148
		$view = new View();
149
		$output->writeln("Analysing files of $this->sourceUser ...");
150
		$progress = new ProgressBar($output);
151
		$progress->start();
152
		$self = $this;
153
		$this->walkFiles($view, "$this->sourceUser/files",
154
				function (FileInfo $fileInfo) use ($progress, $self) {
155
					if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
156
						// only analyze into folders from main storage,
157
						// sub-storages have an empty internal path
158
						if ($fileInfo->getInternalPath() === '' && $fileInfo->getPath() !== '') {
159
							return false;
160
						}
161
						return true;
162
					}
163
					$progress->advance();
164
					$this->allFiles[] = $fileInfo;
165
					if ($fileInfo->isEncrypted()) {
166
						$this->encryptedFiles[] = $fileInfo;
167
					}
168
					return true;
169
				});
170
		$progress->finish();
171
		$output->writeln('');
172
173
		// no file is allowed to be encrypted
174
		if (!empty($this->encryptedFiles)) {
175
			$output->writeln("<error>Some files are encrypted - please decrypt them first</error>");
176
			foreach($this->encryptedFiles as $encryptedFile) {
177
				/** @var FileInfo $encryptedFile */
178
				$output->writeln("  " . $encryptedFile->getPath());
179
			}
180
			throw new \Exception('Execution terminated.');
181
		}
182
183
	}
184
185
	/**
186
	 * @param OutputInterface $output
187
	 */
188
	private function collectUsersShares(OutputInterface $output) {
189
		$output->writeln("Collecting all share information for files and folder of $this->sourceUser ...");
190
191
		$progress = new ProgressBar($output, count($this->shares));
192
		foreach([\OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE] as $shareType) {
193
		$offset = 0;
194
			while (true) {
195
				$sharePage = $this->shareManager->getSharesBy($this->sourceUser, $shareType, null, true, 50, $offset);
196
				$progress->advance(count($sharePage));
197
				if (empty($sharePage)) {
198
					break;
199
				}
200
				$this->shares = array_merge($this->shares, $sharePage);
201
				$offset += 50;
202
			}
203
		}
204
205
		$progress->finish();
206
		$output->writeln('');
207
	}
208
209
	/**
210
	 * @param OutputInterface $output
211
	 */
212
	protected function transfer(OutputInterface $output) {
213
		$view = new View();
214
		$output->writeln("Transferring files to $this->finalTarget ...");
215
		$view->rename("$this->sourceUser/files", $this->finalTarget);
216
		// because the files folder is moved away we need to recreate it
217
		$view->mkdir("$this->sourceUser/files");
218
	}
219
220
	/**
221
	 * @param OutputInterface $output
222
	 */
223
	private function restoreShares(OutputInterface $output) {
224
		$output->writeln("Restoring shares ...");
225
		$progress = new ProgressBar($output, count($this->shares));
226
227
		foreach($this->shares as $share) {
228
			try {
229
				if ($share->getSharedWith() === $this->destinationUser) {
230
					// Unmount the shares before deleting, so we don't try to get the storage later on.
231
					$shareMountPoint = $this->mountManager->find('/' . $this->destinationUser . '/files' . $share->getTarget());
232
					if ($shareMountPoint) {
233
						$this->mountManager->removeMount($shareMountPoint->getMountPoint());
234
					}
235
					$this->shareManager->deleteShare($share);
236
				} else {
237
					if ($share->getShareOwner() === $this->sourceUser) {
238
						$share->setShareOwner($this->destinationUser);
239
					}
240
					if ($share->getSharedBy() === $this->sourceUser) {
241
						$share->setSharedBy($this->destinationUser);
242
					}
243
244
					$this->shareManager->updateShare($share);
245
				}
246
			} catch (\OCP\Files\NotFoundException $e) {
247
				$output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted file, skipping</error>');
248
			} catch (\Exception $e) {
249
				$output->writeln('<error>Could not restore share with id ' . $share->getId() . ':' . $e->getTraceAsString() . '</error>');
250
			}
251
			$progress->advance();
252
		}
253
		$progress->finish();
254
		$output->writeln('');
255
	}
256
}
257