Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ProfileManager.php « Profile « private « lib - github.com/nextcloud/server.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f83de7fd358f28253c6990be4af6e46b257720b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
<?php

declare(strict_types=1);

/**
 * @copyright 2021 Christopher Ng <chrng8@gmail.com>
 *
 * @author Christopher Ng <chrng8@gmail.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OC\Profile;

use function Safe\array_flip;
use function Safe\usort;
use OC\AppFramework\Bootstrap\Coordinator;
use OC\Core\Db\ProfileConfig;
use OC\Core\Db\ProfileConfigMapper;
use OC\KnownUser\KnownUserService;
use OC\Profile\Actions\EmailAction;
use OC\Profile\Actions\PhoneAction;
use OC\Profile\Actions\TwitterAction;
use OC\Profile\Actions\WebsiteAction;
use OCP\Accounts\IAccountManager;
use OCP\Accounts\PropertyDoesNotExistException;
use OCP\App\IAppManager;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\IUser;
use OCP\L10N\IFactory;
use OCP\Profile\ILinkAction;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

class ProfileManager {

	/** @var IAccountManager */
	private $accountManager;

	/** @var IAppManager */
	private $appManager;

	/** @var ProfileConfigMapper */
	private $configMapper;

	/** @var ContainerInterface */
	private $container;

	/** @var KnownUserService */
	private $knownUserService;

	/** @var IFactory */
	private $l10nFactory;

	/** @var LoggerInterface */
	private $logger;

	/** @var Coordinator */
	private $coordinator;

	/** @var ILinkAction[] */
	private $actions = [];

	/** @var null|ILinkAction[] */
	private $sortedActions = null;

	private const CORE_APP_ID = 'core';

	/**
	 * Array of account property actions
	 */
	private const ACCOUNT_PROPERTY_ACTIONS = [
		EmailAction::class,
		PhoneAction::class,
		WebsiteAction::class,
		TwitterAction::class,
	];

	/**
	 * Array of account properties displayed on the profile
	 */
	private const PROFILE_PROPERTIES = [
		IAccountManager::PROPERTY_ADDRESS,
		IAccountManager::PROPERTY_AVATAR,
		IAccountManager::PROPERTY_BIOGRAPHY,
		IAccountManager::PROPERTY_DISPLAYNAME,
		IAccountManager::PROPERTY_HEADLINE,
		IAccountManager::PROPERTY_ORGANISATION,
		IAccountManager::PROPERTY_ROLE,
	];

	public function __construct(
		IAccountManager $accountManager,
		IAppManager $appManager,
		ProfileConfigMapper $configMapper,
		ContainerInterface $container,
		KnownUserService $knownUserService,
		IFactory $l10nFactory,
		LoggerInterface $logger,
		Coordinator $coordinator
	) {
		$this->accountManager = $accountManager;
		$this->appManager = $appManager;
		$this->configMapper = $configMapper;
		$this->container = $container;
		$this->knownUserService = $knownUserService;
		$this->l10nFactory = $l10nFactory;
		$this->logger = $logger;
		$this->coordinator = $coordinator;
	}

	/**
	 * Register an action for the user
	 */
	private function registerAction(ILinkAction $action, IUser $targetUser, ?IUser $visitingUser): void {
		$action->preload($targetUser);

		if ($action->getTarget() === null) {
			// Actions without a target are not registered
			return;
		}

		if ($action->getAppId() !== self::CORE_APP_ID) {
			if (!$this->appManager->isEnabledForUser($action->getAppId(), $targetUser)) {
				$this->logger->notice('App: ' . $action->getAppId() . ' cannot register actions as it is not enabled for the target user: ' . $targetUser->getUID());
				return;
			}
			if (!$this->appManager->isEnabledForUser($action->getAppId(), $visitingUser)) {
				$this->logger->notice('App: ' . $action->getAppId() . ' cannot register actions as it is not enabled for the visiting user: ' . $visitingUser->getUID());
				return;
			}
		}

		if (in_array($action->getId(), self::PROFILE_PROPERTIES, true)) {
			$this->logger->error('Cannot register action with ID: ' . $action->getId() . ', as it is used by a core account property.');
			return;
		}

		if (isset($this->actions[$action->getId()])) {
			$this->logger->error('Cannot register duplicate action: ' . $action->getId());
			return;
		}

		// Add action to associative array of actions
		$this->actions[$action->getId()] = $action;
	}

	/**
	 * Return an array of registered profile actions for the user
	 *
	 * @return ILinkAction[]
	 */
	private function getActions(IUser $targetUser, ?IUser $visitingUser): array {
		// If actions are already registered and sorted, return them
		if ($this->sortedActions !== null) {
			return $this->sortedActions;
		}

		foreach (self::ACCOUNT_PROPERTY_ACTIONS as $actionClass) {
			/** @var ILinkAction $action */
			$action = $this->container->get($actionClass);
			$this->registerAction($action, $targetUser, $visitingUser);
		}

		$context = $this->coordinator->getRegistrationContext();

		if ($context !== null) {
			foreach ($context->getProfileLinkActions() as $registration) {
				/** @var ILinkAction $action */
				$action = $this->container->get($registration->getService());
				$this->registerAction($action, $targetUser, $visitingUser);
			}
		}

		$actionsClone = $this->actions;
		// Sort associative array into indexed array in ascending order of priority
		usort($actionsClone, function (ILinkAction $a, ILinkAction $b) {
			return $a->getPriority() === $b->getPriority() ? 0 : ($a->getPriority() < $b->getPriority() ? -1 : 1);
		});

		$this->sortedActions = $actionsClone;
		return $this->sortedActions;
	}

	/**
	 * Return whether the profile parameter of the target user
	 * is visible to the visiting user
	 */
	private function isParameterVisible(string $paramId, IUser $targetUser, ?IUser $visitingUser): bool {
		try {
			$account = $this->accountManager->getAccount($targetUser);
			$scope = $account->getProperty($paramId)->getScope();
		} catch (PropertyDoesNotExistException $e) {
			// Allow the exception as not all profile parameters are account properties
		}

		$visibility = $this->getProfileConfig($targetUser, $visitingUser)[$paramId]['visibility'];
		// Handle profile visibility and account property scope
		switch ($visibility) {
			case ProfileConfig::VISIBILITY_HIDE:
				return false;
			case ProfileConfig::VISIBILITY_SHOW_USERS_ONLY:
				if (!empty($scope)) {
					switch ($scope) {
						case IAccountManager::SCOPE_PRIVATE:
							return $visitingUser !== null && $this->knownUserService->isKnownToUser($targetUser->getUID(), $visitingUser->getUID());
						case IAccountManager::SCOPE_LOCAL:
						case IAccountManager::SCOPE_FEDERATED:
						case IAccountManager::SCOPE_PUBLISHED:
							return $visitingUser !== null;
						default:
							return false;
					}
				}
				return $visitingUser !== null;
			case ProfileConfig::VISIBILITY_SHOW:
				if (!empty($scope)) {
					switch ($scope) {
						case IAccountManager::SCOPE_PRIVATE:
							return $visitingUser !== null && $this->knownUserService->isKnownToUser($targetUser->getUID(), $visitingUser->getUID());
						case IAccountManager::SCOPE_LOCAL:
						case IAccountManager::SCOPE_FEDERATED:
						case IAccountManager::SCOPE_PUBLISHED:
							return true;
						default:
							return false;
					}
				}
				return true;
			default:
				return false;
		}
	}

	/**
	 * Return the profile parameters of the target user that are visible to the visiting user
	 * in an associative array
	 */
	public function getProfileParams(IUser $targetUser, ?IUser $visitingUser): array {
		$account = $this->accountManager->getAccount($targetUser);

		// Initialize associative array of profile parameters
		$profileParameters = [
			'userId' => $account->getUser()->getUID(),
		];

		// Add account properties
		foreach (self::PROFILE_PROPERTIES as $property) {
			switch ($property) {
				case IAccountManager::PROPERTY_ADDRESS:
				case IAccountManager::PROPERTY_BIOGRAPHY:
				case IAccountManager::PROPERTY_DISPLAYNAME:
				case IAccountManager::PROPERTY_HEADLINE:
				case IAccountManager::PROPERTY_ORGANISATION:
				case IAccountManager::PROPERTY_ROLE:
					$profileParameters[$property] =
						$this->isParameterVisible($property, $targetUser, $visitingUser)
						// Explicitly set to null when value is empty string
						? ($account->getProperty($property)->getValue() ?: null)
						: null;
					break;
				case IAccountManager::PROPERTY_AVATAR:
					// Add avatar visibility
					$profileParameters['isUserAvatarVisible'] = $this->isParameterVisible($property, $targetUser, $visitingUser);
					break;
			}
		}

		// Add actions
		$profileParameters['actions'] = array_map(
			function (ILinkAction $action) {
				return [
					'id' => $action->getId(),
					'icon' => $action->getIcon(),
					'title' => $action->getTitle(),
					'target' => $action->getTarget(),
				];
			},
			// This is needed to reindex the array after filtering
			array_values(
				array_filter(
					$this->getActions($targetUser, $visitingUser),
					function (ILinkAction $action) use ($targetUser, $visitingUser) {
						return $this->isParameterVisible($action->getId(), $targetUser, $visitingUser);
					}
				),
			)
		);

		return $profileParameters;
	}

	/**
	 * Return the filtered profile config containing only
	 * the properties to be stored on the database
	 */
	private function filterNotStoredProfileConfig(array $profileConfig): array {
		$dbParamConfigProperties = [
			'visibility',
		];

		foreach ($profileConfig as $paramId => $paramConfig) {
			$profileConfig[$paramId] = array_intersect_key($paramConfig, array_flip($dbParamConfigProperties));
		}

		return $profileConfig;
	}

	/**
	 * Return the default profile config
	 */
	private function getDefaultProfileConfig(IUser $targetUser, ?IUser $visitingUser): array {
		// Contruct the default config for actions
		$actionsConfig = [];
		foreach ($this->getActions($targetUser, $visitingUser) as $action) {
			$actionsConfig[$action->getId()] = ['visibility' => ProfileConfig::DEFAULT_VISIBILITY];
		}

		// Contruct the default config for account properties
		$propertiesConfig = [];
		foreach (ProfileConfig::DEFAULT_PROPERTY_VISIBILITY as $property => $visibility) {
			$propertiesConfig[$property] = ['visibility' => $visibility];
		}

		return array_merge($actionsConfig, $propertiesConfig);
	}

	/**
	 * Return the profile config of the target user,
	 * if a config does not already exist a default config is created and returned
	 */
	public function getProfileConfig(IUser $targetUser, ?IUser $visitingUser): array {
		$defaultProfileConfig = $this->getDefaultProfileConfig($targetUser, $visitingUser);
		try {
			$config = $this->configMapper->get($targetUser->getUID());
			// Merge defaults with the existing config in case the defaults are missing
			$config->setConfigArray(array_merge(
				$defaultProfileConfig,
				$this->filterNotStoredProfileConfig($config->getConfigArray()),
			));
			$this->configMapper->update($config);
			$configArray = $config->getConfigArray();
		} catch (DoesNotExistException $e) {
			// Create a new default config if it does not exist
			$config = new ProfileConfig();
			$config->setUserId($targetUser->getUID());
			$config->setConfigArray($defaultProfileConfig);
			$this->configMapper->insert($config);
			$configArray = $config->getConfigArray();
		}

		return $configArray;
	}

	/**
	 * Return the profile config of the target user with additional medatata,
	 * if a config does not already exist a default config is created and returned
	 */
	public function getProfileConfigWithMetadata(IUser $targetUser, ?IUser $visitingUser): array {
		$configArray = $this->getProfileConfig($targetUser, $visitingUser);

		$actionsMetadata = [];
		foreach ($this->getActions($targetUser, $visitingUser) as $action) {
			$actionsMetadata[$action->getId()] = [
				'appId' => $action->getAppId(),
				'displayId' => $action->getDisplayId(),
			];
		}

		// Add metadata for account property actions which are always configurable
		foreach (self::ACCOUNT_PROPERTY_ACTIONS as $actionClass) {
			/** @var ILinkAction $action */
			$action = $this->container->get($actionClass);
			if (!isset($actionsMetadata[$action->getId()])) {
				$actionsMetadata[$action->getId()] = [
					'appId' => $action->getAppId(),
					'displayId' => $action->getDisplayId(),
				];
			}
		}

		$propertiesMetadata = [
			IAccountManager::PROPERTY_ADDRESS => [
				'appId' => self::CORE_APP_ID,
				'displayId' => $this->l10nFactory->get(self::CORE_APP_ID)->t('Address'),
			],
			IAccountManager::PROPERTY_AVATAR => [
				'appId' => self::CORE_APP_ID,
				'displayId' => $this->l10nFactory->get(self::CORE_APP_ID)->t('Profile picture'),
			],
			IAccountManager::PROPERTY_BIOGRAPHY => [
				'appId' => self::CORE_APP_ID,
				'displayId' => $this->l10nFactory->get(self::CORE_APP_ID)->t('About'),
			],
			IAccountManager::PROPERTY_DISPLAYNAME => [
				'appId' => self::CORE_APP_ID,
				'displayId' => $this->l10nFactory->get(self::CORE_APP_ID)->t('Full name'),
			],
			IAccountManager::PROPERTY_HEADLINE => [
				'appId' => self::CORE_APP_ID,
				'displayId' => $this->l10nFactory->get(self::CORE_APP_ID)->t('Headline'),
			],
			IAccountManager::PROPERTY_ORGANISATION => [
				'appId' => self::CORE_APP_ID,
				'displayId' => $this->l10nFactory->get(self::CORE_APP_ID)->t('Organisation'),
			],
			IAccountManager::PROPERTY_ROLE => [
				'appId' => self::CORE_APP_ID,
				'displayId' => $this->l10nFactory->get(self::CORE_APP_ID)->t('Role'),
			],
		];

		$paramMetadata = array_merge($actionsMetadata, $propertiesMetadata);

		foreach ($configArray as $paramId => $paramConfig) {
			if (isset($paramMetadata[$paramId])) {
				$configArray[$paramId] = array_merge(
					$paramConfig,
					$paramMetadata[$paramId],
				);
			}
		}

		return $configArray;
	}
}