Passed
Push — master ( 3f0748...19712e )
by Roeland
36:01 queued 24:20
created

MountProvider::groupShares()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 6
nop 1
dl 0
loc 25
rs 8.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Christoph Wurst <[email protected]>
6
 * @author Daniel Calviño Sánchez <[email protected]>
7
 * @author Joas Schilling <[email protected]>
8
 * @author Maxence Lange <[email protected]>
9
 * @author Morris Jobke <[email protected]>
10
 * @author Robin Appelman <[email protected]>
11
 * @author Roeland Jago Douma <[email protected]>
12
 * @author Vincent Petry <[email protected]>
13
 *
14
 * @license AGPL-3.0
15
 *
16
 * This code is free software: you can redistribute it and/or modify
17
 * it under the terms of the GNU Affero General Public License, version 3,
18
 * as published by the Free Software Foundation.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23
 * GNU Affero General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU Affero General Public License, version 3,
26
 * along with this program. If not, see <http://www.gnu.org/licenses/>
27
 *
28
 */
29
30
namespace OCA\Files_Sharing;
31
32
use OC\Cache\CappedMemoryCache;
33
use OC\Files\View;
34
use OCP\Files\Config\IMountProvider;
35
use OCP\Files\Storage\IStorageFactory;
36
use OCP\IConfig;
37
use OCP\ILogger;
38
use OCP\IUser;
39
use OCP\Share\IManager;
40
use OCP\Share\IShare;
41
42
class MountProvider implements IMountProvider {
43
	/**
44
	 * @var \OCP\IConfig
45
	 */
46
	protected $config;
47
48
	/**
49
	 * @var IManager
50
	 */
51
	protected $shareManager;
52
53
	/**
54
	 * @var ILogger
55
	 */
56
	protected $logger;
57
58
	/**
59
	 * @param \OCP\IConfig $config
60
	 * @param IManager $shareManager
61
	 * @param ILogger $logger
62
	 */
63
	public function __construct(IConfig $config, IManager $shareManager, ILogger $logger) {
64
		$this->config = $config;
65
		$this->shareManager = $shareManager;
66
		$this->logger = $logger;
67
	}
68
69
70
	/**
71
	 * Get all mountpoints applicable for the user and check for shares where we need to update the etags
72
	 *
73
	 * @param \OCP\IUser $user
74
	 * @param \OCP\Files\Storage\IStorageFactory $storageFactory
75
	 * @return \OCP\Files\Mount\IMountPoint[]
76
	 */
77
	public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) {
78
		$shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1);
0 ignored issues
show
Deprecated Code introduced by
The constant OC\Share\Constants::SHARE_TYPE_USER has been deprecated: 17.0.0 - use IShare::TYPE_USER instead ( Ignorable by Annotation )

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

78
		$shares = $this->shareManager->getSharedWith($user->getUID(), /** @scrutinizer ignore-deprecated */ \OCP\Share::SHARE_TYPE_USER, null, -1);

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
79
		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1));
0 ignored issues
show
Deprecated Code introduced by
The constant OC\Share\Constants::SHARE_TYPE_GROUP has been deprecated: 17.0.0 - use IShare::TYPE_GROUP instead ( Ignorable by Annotation )

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

79
		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), /** @scrutinizer ignore-deprecated */ \OCP\Share::SHARE_TYPE_GROUP, null, -1));

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
80
		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_CIRCLE, null, -1));
0 ignored issues
show
Deprecated Code introduced by
The constant OC\Share\Constants::SHARE_TYPE_CIRCLE has been deprecated: 17.0.0 - use IShare::TYPE_CIRCLE instead ( Ignorable by Annotation )

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

80
		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), /** @scrutinizer ignore-deprecated */ \OCP\Share::SHARE_TYPE_CIRCLE, null, -1));

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
81
		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_ROOM, null, -1));
0 ignored issues
show
Deprecated Code introduced by
The constant OC\Share\Constants::SHARE_TYPE_ROOM has been deprecated: 17.0.0 - use IShare::TYPE_ROOM instead ( Ignorable by Annotation )

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

81
		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), /** @scrutinizer ignore-deprecated */ \OCP\Share::SHARE_TYPE_ROOM, null, -1));

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
82
83
		// filter out excluded shares and group shares that includes self
84
		$shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
85
			return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
86
		});
87
88
		$superShares = $this->buildSuperShares($shares, $user);
89
90
		$mounts = [];
91
		$view = new View('/' . $user->getUID() . '/files');
92
		$ownerViews = [];
93
		$sharingDisabledForUser = $this->shareManager->sharingDisabledForUser($user->getUID());
94
		$foldersExistCache = new CappedMemoryCache();
95
		foreach ($superShares as $share) {
96
			try {
97
				/** @var \OCP\Share\IShare $parentShare */
98
				$parentShare = $share[0];
99
100
				if ($parentShare->getStatus() !== IShare::STATUS_ACCEPTED &&
101
					($parentShare->getShareType() === IShare::TYPE_GROUP ||
102
						$parentShare->getShareType() === IShare::TYPE_USERGROUP ||
103
						$parentShare->getShareType() === IShare::TYPE_USER)) {
104
					continue;
105
				}
106
107
				$owner = $parentShare->getShareOwner();
108
				if (!isset($ownerViews[$owner])) {
109
					$ownerViews[$owner] = new View('/' . $parentShare->getShareOwner() . '/files');
110
				}
111
				$mount = new SharedMount(
112
					'\OCA\Files_Sharing\SharedStorage',
113
					$mounts,
114
					[
115
						'user' => $user->getUID(),
116
						// parent share
117
						'superShare' => $parentShare,
118
						// children/component of the superShare
119
						'groupedShares' => $share[1],
120
						'ownerView' => $ownerViews[$owner],
121
						'sharingDisabledForUser' => $sharingDisabledForUser
122
					],
123
					$storageFactory,
124
					$view,
125
					$foldersExistCache
126
				);
127
				$mounts[$mount->getMountPoint()] = $mount;
128
			} catch (\Exception $e) {
129
				$this->logger->logException($e);
130
				$this->logger->error('Error while trying to create shared mount');
131
			}
132
		}
133
134
		// array_filter removes the null values from the array
135
		return array_values(array_filter($mounts));
136
	}
137
138
	/**
139
	 * Groups shares by path (nodeId) and target path
140
	 *
141
	 * @param \OCP\Share\IShare[] $shares
142
	 * @return \OCP\Share\IShare[][] array of grouped shares, each element in the
143
	 * array is a group which itself is an array of shares
144
	 */
145
	private function groupShares(array $shares) {
146
		$tmp = [];
147
148
		foreach ($shares as $share) {
149
			if (!isset($tmp[$share->getNodeId()])) {
150
				$tmp[$share->getNodeId()] = [];
151
			}
152
			$tmp[$share->getNodeId()][] = $share;
153
		}
154
155
		$result = [];
156
		// sort by stime, the super share will be based on the least recent share
157
		foreach ($tmp as &$tmp2) {
158
			@usort($tmp2, function ($a, $b) {
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for usort(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

158
			/** @scrutinizer ignore-unhandled */ @usort($tmp2, function ($a, $b) {

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
159
				$aTime = $a->getShareTime()->getTimestamp();
160
				$bTime = $b->getShareTime()->getTimestamp();
161
				if ($aTime === $bTime) {
162
					return $a->getId() < $b->getId() ? -1 : 1;
163
				}
164
				return $aTime < $bTime ? -1 : 1;
165
			});
166
			$result[] = $tmp2;
167
		}
168
169
		return array_values($result);
170
	}
171
172
	/**
173
	 * Build super shares (virtual share) by grouping them by node id and target,
174
	 * then for each group compute the super share and return it along with the matching
175
	 * grouped shares. The most permissive permissions are used based on the permissions
176
	 * of all shares within the group.
177
	 *
178
	 * @param \OCP\Share\IShare[] $allShares
179
	 * @param \OCP\IUser $user user
180
	 * @return array Tuple of [superShare, groupedShares]
181
	 */
182
	private function buildSuperShares(array $allShares, \OCP\IUser $user) {
183
		$result = [];
184
185
		$groupedShares = $this->groupShares($allShares);
186
187
		/** @var \OCP\Share\IShare[] $shares */
188
		foreach ($groupedShares as $shares) {
189
			if (count($shares) === 0) {
190
				continue;
191
			}
192
193
			$superShare = $this->shareManager->newShare();
194
195
			// compute super share based on first entry of the group
196
			$superShare->setId($shares[0]->getId())
197
				->setShareOwner($shares[0]->getShareOwner())
198
				->setNodeId($shares[0]->getNodeId())
199
				->setShareType($shares[0]->getShareType())
200
				->setTarget($shares[0]->getTarget());
201
202
			// use most permissive permissions
203
			$permissions = 0;
204
			$status = IShare::STATUS_PENDING;
205
			foreach ($shares as $share) {
206
				$permissions |= $share->getPermissions();
207
				$status = max($status, $share->getStatus());
208
209
				if ($share->getTarget() !== $superShare->getTarget()) {
210
					// adjust target, for database consistency
211
					$share->setTarget($superShare->getTarget());
212
					try {
213
						$this->shareManager->moveShare($share, $user->getUID());
214
					} catch (\InvalidArgumentException $e) {
215
						// ignore as it is not important and we don't want to
216
						// block FS setup
217
218
						// the subsequent code anyway only uses the target of the
219
						// super share
220
221
						// such issue can usually happen when dealing with
222
						// null groups which usually appear with group backend
223
						// caching inconsistencies
224
						$this->logger->debug(
225
							'Could not adjust share target for share ' . $share->getId() . ' to make it consistent: ' . $e->getMessage(),
226
							['app' => 'files_sharing']
227
						);
228
					}
229
				}
230
				if (!is_null($share->getNodeCacheEntry())) {
231
					$superShare->setNodeCacheEntry($share->getNodeCacheEntry());
232
				}
233
			}
234
235
			$superShare->setPermissions($permissions)
236
				->setStatus($status);
237
238
			$result[] = [$superShare, $shares];
239
		}
240
241
		return $result;
242
	}
243
}
244