AUserData::getUserData()   F
last analyzed

Complexity

Conditions 20
Paths > 20000

Size

Total Lines 115
Code Lines 76

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 20
eloc 76
nc 20694
nop 2
dl 0
loc 115
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @copyright Copyright (c) 2018 John Molakvoæ (skjnldsv) <[email protected]>
7
 *
8
 * @author Arthur Schiwon <[email protected]>
9
 * @author Christoph Wurst <[email protected]>
10
 * @author Georg Ehrke <[email protected]>
11
 * @author Joas Schilling <[email protected]>
12
 * @author John Molakvoæ <[email protected]>
13
 * @author Roeland Jago Douma <[email protected]>
14
 * @author Vincent Petry <[email protected]>
15
 * @author Kate Döen <[email protected]>
16
 *
17
 * @license GNU AGPL version 3 or any later version
18
 *
19
 * This program is free software: you can redistribute it and/or modify
20
 * it under the terms of the GNU Affero General Public License as
21
 * published by the Free Software Foundation, either version 3 of the
22
 * License, or (at your option) any later version.
23
 *
24
 * This program is distributed in the hope that it will be useful,
25
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27
 * GNU Affero General Public License for more details.
28
 *
29
 * You should have received a copy of the GNU Affero General Public License
30
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31
 *
32
 */
33
namespace OCA\Provisioning_API\Controller;
34
35
use OC\Group\Manager;
36
use OC\User\Backend;
37
use OC\User\NoUserException;
38
use OC_Helper;
39
use OCP\Accounts\IAccountManager;
40
use OCP\Accounts\PropertyDoesNotExistException;
41
use OCP\AppFramework\Http;
42
use OCP\AppFramework\OCS\OCSException;
43
use OCP\AppFramework\OCS\OCSNotFoundException;
44
use OCP\AppFramework\OCSController;
45
use OCP\Files\NotFoundException;
46
use OCP\IConfig;
47
use OCP\IGroupManager;
48
use OCP\IRequest;
49
use OCP\IUserManager;
50
use OCP\IUserSession;
51
use OCP\L10N\IFactory;
52
use OCP\User\Backend\ISetDisplayNameBackend;
53
use OCP\User\Backend\ISetPasswordBackend;
54
55
abstract class AUserData extends OCSController {
56
	public const SCOPE_SUFFIX = 'Scope';
57
58
	public const USER_FIELD_DISPLAYNAME = 'display';
59
	public const USER_FIELD_LANGUAGE = 'language';
60
	public const USER_FIELD_LOCALE = 'locale';
61
	public const USER_FIELD_PASSWORD = 'password';
62
	public const USER_FIELD_QUOTA = 'quota';
63
	public const USER_FIELD_MANAGER = 'manager';
64
	public const USER_FIELD_NOTIFICATION_EMAIL = 'notify_email';
65
66
	/** @var IUserManager */
67
	protected $userManager;
68
	/** @var IConfig */
69
	protected $config;
70
	/** @var Manager */
71
	protected $groupManager;
72
	/** @var IUserSession */
73
	protected $userSession;
74
	/** @var IAccountManager */
75
	protected $accountManager;
76
	/** @var IFactory */
77
	protected $l10nFactory;
78
79
	public function __construct(string $appName,
80
								IRequest $request,
81
								IUserManager $userManager,
82
								IConfig $config,
83
								IGroupManager $groupManager,
84
								IUserSession $userSession,
85
								IAccountManager $accountManager,
86
								IFactory $l10nFactory) {
87
		parent::__construct($appName, $request);
88
89
		$this->userManager = $userManager;
90
		$this->config = $config;
91
		$this->groupManager = $groupManager;
0 ignored issues
show
Documentation Bug introduced by
$groupManager is of type OCP\IGroupManager, but the property $groupManager was declared to be of type OC\Group\Manager. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
92
		$this->userSession = $userSession;
93
		$this->accountManager = $accountManager;
94
		$this->l10nFactory = $l10nFactory;
95
	}
96
97
	/**
98
	 * creates a array with all user data
99
	 *
100
	 * @param string $userId
101
	 * @param bool $includeScopes
102
	 * @return array
103
	 * @throws NotFoundException
104
	 * @throws OCSException
105
	 * @throws OCSNotFoundException
106
	 */
107
	protected function getUserData(string $userId, bool $includeScopes = false): array {
108
		$currentLoggedInUser = $this->userSession->getUser();
109
		assert($currentLoggedInUser !== null, 'No user logged in');
110
111
		$data = [];
112
113
		// Check if the target user exists
114
		$targetUserObject = $this->userManager->get($userId);
115
		if ($targetUserObject === null) {
116
			throw new OCSNotFoundException('User does not exist');
117
		}
118
119
		$isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
120
		if ($isAdmin
121
			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
122
			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true') === 'true';
123
		} else {
124
			// Check they are looking up themselves
125
			if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
126
				return $data;
127
			}
128
		}
129
130
		// Get groups data
131
		$userAccount = $this->accountManager->getAccount($targetUserObject);
132
		$groups = $this->groupManager->getUserGroups($targetUserObject);
133
		$gids = [];
134
		foreach ($groups as $group) {
135
			$gids[] = $group->getGID();
136
		}
137
138
		if ($isAdmin) {
139
			try {
140
				# might be thrown by LDAP due to handling of users disappears
141
				# from the external source (reasons unknown to us)
142
				# cf. https://github.com/nextcloud/server/issues/12991
143
				$data['storageLocation'] = $targetUserObject->getHome();
144
			} catch (NoUserException $e) {
145
				throw new OCSNotFoundException($e->getMessage(), $e);
146
			}
147
		}
148
149
		// Find the data
150
		$data['id'] = $targetUserObject->getUID();
151
		$data['lastLogin'] = $targetUserObject->getLastLogin() * 1000;
152
		$data['backend'] = $targetUserObject->getBackendClassName();
153
		$data['subadmin'] = $this->getUserSubAdminGroupsData($targetUserObject->getUID());
154
		$data[self::USER_FIELD_QUOTA] = $this->fillStorageInfo($targetUserObject->getUID());
155
		$managerUids = $targetUserObject->getManagerUids();
156
		$data[self::USER_FIELD_MANAGER] = empty($managerUids) ? '' : $managerUids[0];
157
158
		try {
159
			if ($includeScopes) {
160
				$data[IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope();
161
			}
162
163
			$data[IAccountManager::PROPERTY_EMAIL] = $targetUserObject->getSystemEMailAddress();
164
			if ($includeScopes) {
165
				$data[IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getScope();
166
			}
167
168
			$additionalEmails = $additionalEmailScopes = [];
169
			$emailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
170
			foreach ($emailCollection->getProperties() as $property) {
171
				$additionalEmails[] = $property->getValue();
172
				if ($includeScopes) {
173
					$additionalEmailScopes[] = $property->getScope();
174
				}
175
			}
176
			$data[IAccountManager::COLLECTION_EMAIL] = $additionalEmails;
177
			if ($includeScopes) {
178
				$data[IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX] = $additionalEmailScopes;
179
			}
180
181
			$data[IAccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
182
			$data[IAccountManager::PROPERTY_DISPLAYNAME_LEGACY] = $data[IAccountManager::PROPERTY_DISPLAYNAME];
183
			if ($includeScopes) {
184
				$data[IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getScope();
185
			}
186
187
			foreach ([
188
				IAccountManager::PROPERTY_PHONE,
189
				IAccountManager::PROPERTY_ADDRESS,
190
				IAccountManager::PROPERTY_WEBSITE,
191
				IAccountManager::PROPERTY_TWITTER,
192
				IAccountManager::PROPERTY_FEDIVERSE,
193
				IAccountManager::PROPERTY_ORGANISATION,
194
				IAccountManager::PROPERTY_ROLE,
195
				IAccountManager::PROPERTY_HEADLINE,
196
				IAccountManager::PROPERTY_BIOGRAPHY,
197
				IAccountManager::PROPERTY_PROFILE_ENABLED,
198
			] as $propertyName) {
199
				$property = $userAccount->getProperty($propertyName);
200
				$data[$propertyName] = $property->getValue();
201
				if ($includeScopes) {
202
					$data[$propertyName . self::SCOPE_SUFFIX] = $property->getScope();
203
				}
204
			}
205
		} catch (PropertyDoesNotExistException $e) {
206
			// hard coded properties should exist
207
			throw new OCSException($e->getMessage(), Http::STATUS_INTERNAL_SERVER_ERROR, $e);
208
		}
209
210
		$data['groups'] = $gids;
211
		$data[self::USER_FIELD_LANGUAGE] = $this->l10nFactory->getUserLanguage($targetUserObject);
212
		$data[self::USER_FIELD_LOCALE] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'locale');
213
		$data[self::USER_FIELD_NOTIFICATION_EMAIL] = $targetUserObject->getPrimaryEMailAddress();
214
215
		$backend = $targetUserObject->getBackend();
216
		$data['backendCapabilities'] = [
217
			'setDisplayName' => $backend instanceof ISetDisplayNameBackend || $backend->implementsActions(Backend::SET_DISPLAYNAME),
218
			'setPassword' => $backend instanceof ISetPasswordBackend || $backend->implementsActions(Backend::SET_PASSWORD),
219
		];
220
221
		return $data;
222
	}
223
224
	/**
225
	 * Get the groups a user is a subadmin of
226
	 *
227
	 * @param string $userId
228
	 * @return array
229
	 * @throws OCSException
230
	 */
231
	protected function getUserSubAdminGroupsData(string $userId): array {
232
		$user = $this->userManager->get($userId);
233
		// Check if the user exists
234
		if ($user === null) {
235
			throw new OCSNotFoundException('User does not exist');
236
		}
237
238
		// Get the subadmin groups
239
		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
240
		$groups = [];
241
		foreach ($subAdminGroups as $key => $group) {
242
			$groups[] = $group->getGID();
243
		}
244
245
		return $groups;
246
	}
247
248
	/**
249
	 * @param string $userId
250
	 * @return array
251
	 * @throws OCSException
252
	 */
253
	protected function fillStorageInfo(string $userId): array {
254
		try {
255
			\OC_Util::tearDownFS();
256
			\OC_Util::setupFS($userId);
257
			$storage = OC_Helper::getStorageInfo('/', null, true, false);
258
			$data = [
259
				'free' => $storage['free'],
260
				'used' => $storage['used'],
261
				'total' => $storage['total'],
262
				'relative' => $storage['relative'],
263
				self::USER_FIELD_QUOTA => $storage['quota'],
264
			];
265
		} catch (NotFoundException $ex) {
266
			// User fs is not setup yet
267
			$user = $this->userManager->get($userId);
268
			if ($user === null) {
269
				throw new OCSException('User does not exist', 101);
270
			}
271
			$quota = $user->getQuota();
272
			if ($quota !== 'none') {
273
				$quota = OC_Helper::computerFileSize($quota);
274
			}
275
			$data = [
276
				self::USER_FIELD_QUOTA => $quota !== false ? $quota : 'none',
277
				'used' => 0
278
			];
279
		} catch (\Exception $e) {
280
			\OC::$server->get(\Psr\Log\LoggerInterface::class)->error(
281
				"Could not load storage info for {user}",
282
				[
283
					'app' => 'provisioning_api',
284
					'user' => $userId,
285
					'exception' => $e,
286
				]
287
			);
288
			/* In case the Exception left things in a bad state */
289
			\OC_Util::tearDownFS();
290
			return [];
291
		}
292
		return $data;
293
	}
294
}
295