Completed
Push — stable10 ( 65dd17...7321ba )
by Björn
10:16
created

RepairUnmergedShares::isThisShareValid()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
eloc 9
c 1
b 0
f 1
nc 4
nop 2
dl 0
loc 21
rs 9.0534
1
<?php
2
/**
3
 * @author Vincent Petry <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2016, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OC\Repair;
23
24
use OCP\Migration\IOutput;
25
use OCP\Migration\IRepairStep;
26
use OC\Share\Constants;
27
use OCP\DB\QueryBuilder\IQueryBuilder;
28
use OCP\IConfig;
29
use OCP\IDBConnection;
30
use OCP\IUserManager;
31
use OCP\IUser;
32
use OCP\IGroupManager;
33
use OC\Share20\DefaultShareProvider;
34
35
/**
36
 * Repairs shares for which the received folder was not properly deduplicated.
37
 *
38
 * An unmerged share can for example happen when sharing a folder with the same
39
 * user through multiple ways, like several groups and also directly, additionally
40
 * to group shares. Since 9.0.0 these would create duplicate entries "folder (2)",
41
 * one for every share. This repair step rearranges them so they only appear as a single
42
 * folder.
43
 */
44
class RepairUnmergedShares implements IRepairStep {
45
46
	/** @var \OCP\IConfig */
47
	protected $config;
48
49
	/** @var \OCP\IDBConnection */
50
	protected $connection;
51
52
	/** @var IUserManager */
53
	protected $userManager;
54
55
	/** @var IGroupManager */
56
	protected $groupManager;
57
58
	/** @var IQueryBuilder */
59
	private $queryGetSharesWithUsers;
60
61
	/** @var IQueryBuilder */
62
	private $queryUpdateSharePermissionsAndTarget;
63
64
	/** @var IQueryBuilder */
65
	private $queryUpdateShareInBatch;
66
67
	/**
68
	 * @param \OCP\IConfig $config
69
	 * @param \OCP\IDBConnection $connection
70
	 */
71 View Code Duplication
	public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
		IConfig $config,
73
		IDBConnection $connection,
74
		IUserManager $userManager,
75
		IGroupManager $groupManager
76
	) {
77
		$this->connection = $connection;
78
		$this->config = $config;
79
		$this->userManager = $userManager;
80
		$this->groupManager = $groupManager;
81
	}
82
83
	public function getName() {
84
		return 'Repair unmerged shares';
85
	}
86
87
	/**
88
	 * Builds prepared queries for reuse
89
	 */
90
	private function buildPreparedQueries() {
91
		/**
92
		 * Retrieve shares for a given user/group and share type
93
		 */
94
		$query = $this->connection->getQueryBuilder();
95
		$query
96
			->select('item_source', 'id', 'file_target', 'permissions', 'parent', 'share_type')
0 ignored issues
show
Unused Code introduced by
The call to IQueryBuilder::select() has too many arguments starting with 'id'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
97
			->from('share')
98
			->where($query->expr()->eq('share_type', $query->createParameter('shareType')))
99
			->andWhere($query->expr()->in('share_with', $query->createParameter('shareWiths')))
100
			->andWhere($query->expr()->in('item_type', $query->createParameter('itemTypes')))
101
			->orderBy('item_source', 'ASC')
102
			->addOrderBy('stime', 'ASC');
103
104
		$this->queryGetSharesWithUsers = $query;
105
106
		/**
107
		 * Updates the file_target to the given value for all given share ids.
108
		 *
109
		 * This updates several shares in bulk which is faster than individually.
110
		 */
111
		$query = $this->connection->getQueryBuilder();
112
		$query->update('share')
113
			->set('file_target', $query->createParameter('file_target'))
114
			->where($query->expr()->in('id', $query->createParameter('ids')));
115
116
		$this->queryUpdateShareInBatch = $query;
117
118
		/**
119
		 * Updates the share permissions and target path of a single share.
120
		 */
121
		$query = $this->connection->getQueryBuilder();
122
		$query->update('share')
123
			->set('permissions', $query->createParameter('permissions'))
124
			->set('file_target', $query->createParameter('file_target'))
125
			->where($query->expr()->eq('id', $query->createParameter('shareid')));
126
127
		$this->queryUpdateSharePermissionsAndTarget = $query;
128
129
	}
130
131
	private function getSharesWithUser($shareType, $shareWiths) {
132
		$groupedShares = [];
133
134
		$query = $this->queryGetSharesWithUsers;
135
		$query->setParameter('shareWiths', $shareWiths, IQueryBuilder::PARAM_STR_ARRAY);
136
		$query->setParameter('shareType', $shareType);
137
		$query->setParameter('itemTypes', ['file', 'folder'], IQueryBuilder::PARAM_STR_ARRAY);
138
139
		$shares = $query->execute()->fetchAll();
140
141
		// group by item_source
142
		foreach ($shares as $share) {
143
			if (!isset($groupedShares[$share['item_source']])) {
144
				$groupedShares[$share['item_source']] = [];
145
			}
146
			$groupedShares[$share['item_source']][] = $share;
147
		}
148
		return $groupedShares;
149
	}
150
151
	/**
152
	 * Fix the given received share represented by the set of group shares
153
	 * and matching sub shares
154
	 *
155
	 * @param array $groupShares group share entries
156
	 * @param array $subShares sub share entries
157
	 *
158
	 * @return boolean false if the share was not repaired, true if it was
159
	 */
160
	private function fixThisShare($groupShares, $subShares) {
161
		if (empty($subShares)) {
162
			return false;
163
		}
164
165
		$groupSharesById = [];
166
		foreach ($groupShares as $groupShare) {
167
			$groupSharesById[$groupShare['id']] = $groupShare;
168
		}
169
170
		if ($this->isThisShareValid($groupSharesById, $subShares)) {
171
			return false;
172
		}
173
174
		$targetPath = $groupShares[0]['file_target'];
175
176
		// check whether the user opted out completely of all subshares
177
		$optedOut = true;
178
		foreach ($subShares as $subShare) {
179
			if ((int)$subShare['permissions'] !== 0) {
180
				$optedOut = false;
181
				break;
182
			}
183
		}
184
185
		$shareIds = [];
186
		foreach ($subShares as $subShare) {
187
			// only if the user deleted some subshares but not all, adjust the permissions of that subshare
188
			if (!$optedOut && (int)$subShare['permissions'] === 0 && (int)$subShare['share_type'] === DefaultShareProvider::SHARE_TYPE_USERGROUP) {
189
				// set permissions from parent group share
190
				$permissions = $groupSharesById[$subShare['parent']]['permissions'];
191
192
				// fix permissions and target directly
193
				$query = $this->queryUpdateSharePermissionsAndTarget;
194
				$query->setParameter('shareid', $subShare['id']);
195
				$query->setParameter('file_target', $targetPath);
196
				$query->setParameter('permissions', $permissions);
197
				$query->execute();
198
			} else {
199
				// gather share ids for bulk target update
200
				if ($subShare['file_target'] !== $targetPath) {
201
					$shareIds[] = (int)$subShare['id'];
202
				}
203
			}
204
		}
205
206
		if (!empty($shareIds)) {
207
			$query = $this->queryUpdateShareInBatch;
208
			$query->setParameter('ids', $shareIds, IQueryBuilder::PARAM_INT_ARRAY);
209
			$query->setParameter('file_target', $targetPath);
210
			$query->execute();
211
		}
212
213
		return true;
214
	}
215
216
	/**
217
	 * Checks whether the number of group shares is balanced with the child subshares.
218
	 * If all group shares have exactly one subshare, and the target of every subshare
219
	 * is the same, then the share is valid.
220
	 * If however there is a group share entry that has no matching subshare, it means
221
	 * we're in the bogus situation and the whole share must be repaired
222
	 *
223
	 * @param array $groupSharesById
224
	 * @param array $subShares
225
	 *
226
	 * @return true if the share is valid, false if it needs repair
227
	 */
228
	private function isThisShareValid($groupSharesById, $subShares) {
229
		$foundTargets = [];
230
231
		// every group share needs to have exactly one matching subshare
232
		foreach ($subShares as $subShare) {
233
			$foundTargets[$subShare['file_target']] = true;
234
			if (count($foundTargets) > 1) {
235
				// not all the same target path value => invalid
236
				return false;
237
			}
238
			if (isset($groupSharesById[$subShare['parent']])) {
239
				// remove it from the list as we found it
240
				unset($groupSharesById[$subShare['parent']]);
241
			}
242
		}
243
244
		// if we found one subshare per group entry, the set will be empty.
245
		// If not empty, it means that one of the group shares did not have
246
		// a matching subshare entry.
247
		return empty($groupSharesById);
248
	}
249
250
	/**
251
	 * Detect unmerged received shares and merge them properly
252
	 */
253
	private function fixUnmergedShares(IOutput $out, IUser $user) {
0 ignored issues
show
Unused Code introduced by
The parameter $out is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
254
		$groups = $this->groupManager->getUserGroupIds($user);
255
		if (empty($groups)) {
256
			// user is in no groups, so can't have received group shares
257
			return;
258
		}
259
260
		// get all subshares grouped by item source
261
		$subSharesByItemSource = $this->getSharesWithUser(DefaultShareProvider::SHARE_TYPE_USERGROUP, [$user->getUID()]);
262
263
		// because sometimes one wants to give the user more permissions than the group share
264
		$userSharesByItemSource = $this->getSharesWithUser(Constants::SHARE_TYPE_USER, [$user->getUID()]);
265
266
		if (empty($subSharesByItemSource) && empty($userSharesByItemSource)) {
267
			// nothing to repair for this user, no need to do extra queries
268
			return;
269
		}
270
271
		$groupSharesByItemSource = $this->getSharesWithUser(Constants::SHARE_TYPE_GROUP, $groups);
272
		if (empty($groupSharesByItemSource) && empty($userSharesByItemSource)) {
273
			// nothing to repair for this user
274
			return;
275
		}
276
277
		foreach ($groupSharesByItemSource as $itemSource => $groupShares) {
278
			$subShares = [];
279
			if (isset($subSharesByItemSource[$itemSource])) {
280
				$subShares = $subSharesByItemSource[$itemSource];
281
			}
282
283
			if (isset($userSharesByItemSource[$itemSource])) {
284
				// add it to the subshares to get a similar treatment
285
				$subShares = array_merge($subShares, $userSharesByItemSource[$itemSource]);
286
			}
287
288
			$this->fixThisShare($groupShares, $subShares);
289
		}
290
	}
291
292
	/**
293
	 * Count all the users
294
	 *
295
	 * @return int
296
	 */
297 View Code Duplication
	private function countUsers() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
298
		$allCount = $this->userManager->countUsers();
299
300
		$totalCount = 0;
301
		foreach ($allCount as $backend => $count) {
302
			$totalCount += $count;
303
		}
304
305
		return $totalCount;
306
	}
307
308
	public function run(IOutput $output) {
309
		$ocVersionFromBeforeUpdate = $this->config->getSystemValue('version', '0.0.0');
310
		if (version_compare($ocVersionFromBeforeUpdate, '9.1.0.16', '<')) {
311
			// this situation was only possible between 9.0.0 and 9.0.3 included
312
313
			$function = function(IUser $user) use ($output) {
314
				$this->fixUnmergedShares($output, $user);
315
				$output->advance();
316
			};
317
318
			$this->buildPreparedQueries();
319
320
			$userCount = $this->countUsers();
321
			$output->startProgress($userCount);
322
323
			$this->userManager->callForAllUsers($function);
324
325
			$output->finishProgress();
326
		}
327
	}
328
}
329