Completed
Push — master ( 830834...005b3d )
by Thomas
10:38
created

TransferOwnership::restoreShares()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 7
nop 1
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
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
		$this->sourceUser = $input->getArgument('source-user');
93
		$this->destinationUser = $input->getArgument('destination-user');
94
		if (!$this->userManager->userExists($this->sourceUser)) {
95
			$output->writeln("<error>Unknown source user $this->sourceUser</error>");
96
			return;
97
		}
98
		if (!$this->userManager->userExists($this->destinationUser)) {
99
			$output->writeln("<error>Unknown destination user $this->destinationUser</error>");
100
			return;
101
		}
102
		
103
		// target user has to be ready
104
		if (!\OC::$server->getEncryptionManager()->isReadyForUser($this->destinationUser)) {
105
			$output->writeln("<error>The target user is not ready to accept files. The user has at least to be logged in once.</error>");
106
			return;
107
		}
108
109
		$date = date('c');
110
		$this->finalTarget = "$this->destinationUser/files/transferred from $this->sourceUser on $date";
111
112
		// setup filesystem
113
		Filesystem::initMountPoints($this->sourceUser);
114
		Filesystem::initMountPoints($this->destinationUser);
115
116
		// analyse source folder
117
		$this->analyse($output);
118
119
		// collect all the shares
120
		$this->collectUsersShares($output);
121
122
		// transfer the files
123
		$this->transfer($output);
124
125
		// restore the shares
126
		$this->restoreShares($output);
127
	}
128
129
	private function walkFiles(View $view, $path, \Closure $callBack) {
130
		foreach ($view->getDirectoryContent($path) as $fileInfo) {
131
			if (!$callBack($fileInfo)) {
132
				return;
133
			}
134
			if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
135
				$this->walkFiles($view, $fileInfo->getPath(), $callBack);
136
			}
137
		}
138
	}
139
140
	/**
141
	 * @param OutputInterface $output
142
	 * @throws \Exception
143
	 */
144
	protected function analyse(OutputInterface $output) {
145
		$view = new View();
146
		$output->writeln("Analysing files of $this->sourceUser ...");
147
		$progress = new ProgressBar($output);
148
		$progress->start();
149
		$self = $this;
150
		$this->walkFiles($view, "$this->sourceUser/files",
151
				function (FileInfo $fileInfo) use ($progress, $self) {
152
					if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
153
						return true;
154
					}
155
					$progress->advance();
156
					$this->allFiles[] = $fileInfo;
157
					if ($fileInfo->isEncrypted()) {
158
						$this->encryptedFiles[] = $fileInfo;
159
					}
160
					return true;
161
				});
162
		$progress->finish();
163
		$output->writeln('');
164
165
		// no file is allowed to be encrypted
166
		if (!empty($this->encryptedFiles)) {
167
			$output->writeln("<error>Some files are encrypted - please decrypt them first</error>");
168
			foreach($this->encryptedFiles as $encryptedFile) {
169
				/** @var FileInfo $encryptedFile */
170
				$output->writeln("  " . $encryptedFile->getPath());
171
			}
172
			throw new \Exception('Execution terminated.');
173
		}
174
175
	}
176
177
	/**
178
	 * @param OutputInterface $output
179
	 */
180
	private function collectUsersShares(OutputInterface $output) {
181
		$output->writeln("Collecting all share information for files and folder of $this->sourceUser ...");
182
183
		$progress = new ProgressBar($output, count($this->shares));
184
		foreach([\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE] as $shareType) {
185
		$offset = 0;
186
			while (true) {
187
				$sharePage = $this->shareManager->getSharesBy($this->sourceUser, $shareType, null, true, 50, $offset);
188
				$progress->advance(count($sharePage));
189
				if (empty($sharePage)) {
190
					break;
191
				}
192
				$this->shares = array_merge($this->shares, $sharePage);
193
				$offset += 50;
194
			}
195
		}
196
197
		$progress->finish();
198
		$output->writeln('');
199
	}
200
201
	/**
202
	 * @param OutputInterface $output
203
	 */
204
	protected function transfer(OutputInterface $output) {
205
		$view = new View();
206
		$output->writeln("Transferring files to $this->finalTarget ...");
207
		$view->rename("$this->sourceUser/files", $this->finalTarget);
208
		// because the files folder is moved away we need to recreate it
209
		$view->mkdir("$this->sourceUser/files");
210
	}
211
212
	/**
213
	 * @param OutputInterface $output
214
	 */
215
	private function restoreShares(OutputInterface $output) {
216
		$output->writeln("Restoring shares ...");
217
		$progress = new ProgressBar($output, count($this->shares));
218
219
		foreach($this->shares as $share) {
220
			if ($share->getSharedWith() === $this->destinationUser) {
221
				// Unmount the shares before deleting, so we don't try to get the storage later on.
222
				$shareMountPoint = $this->mountManager->find('/' . $this->destinationUser . '/files' . $share->getTarget());
223
				if ($shareMountPoint) {
224
					$this->mountManager->removeMount($shareMountPoint->getMountPoint());
225
				}
226
				$this->shareManager->deleteShare($share);
227
			} else {
228
				if ($share->getShareOwner() === $this->sourceUser) {
229
					$share->setShareOwner($this->destinationUser);
230
				}
231
				if ($share->getSharedBy() === $this->sourceUser) {
232
					$share->setSharedBy($this->destinationUser);
233
				}
234
235
				$this->shareManager->updateShare($share);
236
			}
237
			$progress->advance();
238
		}
239
		$progress->finish();
240
		$output->writeln('');
241
	}
242
}
243