You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ProfileManager.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright 2021 Christopher Ng <chrng8@gmail.com>
  5. *
  6. * @author Christopher Ng <chrng8@gmail.com>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OC\Profile;
  25. use OC\AppFramework\Bootstrap\Coordinator;
  26. use OC\Core\Db\ProfileConfig;
  27. use OC\Core\Db\ProfileConfigMapper;
  28. use OC\KnownUser\KnownUserService;
  29. use OC\Profile\Actions\EmailAction;
  30. use OC\Profile\Actions\FediverseAction;
  31. use OC\Profile\Actions\PhoneAction;
  32. use OC\Profile\Actions\TwitterAction;
  33. use OC\Profile\Actions\WebsiteAction;
  34. use OCP\Accounts\IAccountManager;
  35. use OCP\Accounts\PropertyDoesNotExistException;
  36. use OCP\App\IAppManager;
  37. use OCP\AppFramework\Db\DoesNotExistException;
  38. use OCP\Cache\CappedMemoryCache;
  39. use OCP\IConfig;
  40. use OCP\IUser;
  41. use OCP\L10N\IFactory;
  42. use OCP\Profile\ILinkAction;
  43. use OCP\Profile\IProfileManager;
  44. use Psr\Container\ContainerInterface;
  45. use Psr\Log\LoggerInterface;
  46. use function array_flip;
  47. use function usort;
  48. class ProfileManager implements IProfileManager {
  49. /** @var ILinkAction[] */
  50. private array $actions = [];
  51. /** @var null|ILinkAction[] */
  52. private ?array $sortedActions = null;
  53. /** @var CappedMemoryCache<ProfileConfig> */
  54. private CappedMemoryCache $configCache;
  55. private const CORE_APP_ID = 'core';
  56. /**
  57. * Array of account property actions
  58. */
  59. private const ACCOUNT_PROPERTY_ACTIONS = [
  60. EmailAction::class,
  61. PhoneAction::class,
  62. WebsiteAction::class,
  63. TwitterAction::class,
  64. FediverseAction::class,
  65. ];
  66. /**
  67. * Array of account properties displayed on the profile
  68. */
  69. private const PROFILE_PROPERTIES = [
  70. IAccountManager::PROPERTY_ADDRESS,
  71. IAccountManager::PROPERTY_AVATAR,
  72. IAccountManager::PROPERTY_BIOGRAPHY,
  73. IAccountManager::PROPERTY_DISPLAYNAME,
  74. IAccountManager::PROPERTY_HEADLINE,
  75. IAccountManager::PROPERTY_ORGANISATION,
  76. IAccountManager::PROPERTY_ROLE,
  77. ];
  78. public function __construct(
  79. private IAccountManager $accountManager,
  80. private IAppManager $appManager,
  81. private IConfig $config,
  82. private ProfileConfigMapper $configMapper,
  83. private ContainerInterface $container,
  84. private KnownUserService $knownUserService,
  85. private IFactory $l10nFactory,
  86. private LoggerInterface $logger,
  87. private Coordinator $coordinator,
  88. ) {
  89. $this->configCache = new CappedMemoryCache();
  90. }
  91. /**
  92. * If no user is passed as an argument return whether profile is enabled globally in `config.php`
  93. */
  94. public function isProfileEnabled(?IUser $user = null): bool {
  95. $profileEnabledGlobally = $this->config->getSystemValueBool('profile.enabled', true);
  96. if (empty($user) || !$profileEnabledGlobally) {
  97. return $profileEnabledGlobally;
  98. }
  99. $account = $this->accountManager->getAccount($user);
  100. return (bool) filter_var(
  101. $account->getProperty(IAccountManager::PROPERTY_PROFILE_ENABLED)->getValue(),
  102. FILTER_VALIDATE_BOOLEAN,
  103. FILTER_NULL_ON_FAILURE,
  104. );
  105. }
  106. /**
  107. * Register an action for the user
  108. */
  109. private function registerAction(ILinkAction $action, IUser $targetUser, ?IUser $visitingUser): void {
  110. $action->preload($targetUser);
  111. if ($action->getTarget() === null) {
  112. // Actions without a target are not registered
  113. return;
  114. }
  115. if ($action->getAppId() !== self::CORE_APP_ID) {
  116. if (!$this->appManager->isEnabledForUser($action->getAppId(), $targetUser)) {
  117. $this->logger->notice('App: ' . $action->getAppId() . ' cannot register actions as it is not enabled for the target user: ' . $targetUser->getUID());
  118. return;
  119. }
  120. if (!$this->appManager->isEnabledForUser($action->getAppId(), $visitingUser)) {
  121. $this->logger->notice('App: ' . $action->getAppId() . ' cannot register actions as it is not enabled for the visiting user: ' . ($visitingUser ? $visitingUser->getUID() : '(user not connected)'));
  122. return;
  123. }
  124. }
  125. if (in_array($action->getId(), self::PROFILE_PROPERTIES, true)) {
  126. $this->logger->error('Cannot register action with ID: ' . $action->getId() . ', as it is used by a core account property.');
  127. return;
  128. }
  129. if (isset($this->actions[$action->getId()])) {
  130. $this->logger->error('Cannot register duplicate action: ' . $action->getId());
  131. return;
  132. }
  133. // Add action to associative array of actions
  134. $this->actions[$action->getId()] = $action;
  135. }
  136. /**
  137. * Return an array of registered profile actions for the user
  138. *
  139. * @return ILinkAction[]
  140. */
  141. private function getActions(IUser $targetUser, ?IUser $visitingUser): array {
  142. // If actions are already registered and sorted, return them
  143. if ($this->sortedActions !== null) {
  144. return $this->sortedActions;
  145. }
  146. foreach (self::ACCOUNT_PROPERTY_ACTIONS as $actionClass) {
  147. /** @var ILinkAction $action */
  148. $action = $this->container->get($actionClass);
  149. $this->registerAction($action, $targetUser, $visitingUser);
  150. }
  151. $context = $this->coordinator->getRegistrationContext();
  152. if ($context !== null) {
  153. foreach ($context->getProfileLinkActions() as $registration) {
  154. /** @var ILinkAction $action */
  155. $action = $this->container->get($registration->getService());
  156. $this->registerAction($action, $targetUser, $visitingUser);
  157. }
  158. }
  159. $actionsClone = $this->actions;
  160. // Sort associative array into indexed array in ascending order of priority
  161. usort($actionsClone, function (ILinkAction $a, ILinkAction $b) {
  162. return $a->getPriority() === $b->getPriority() ? 0 : ($a->getPriority() < $b->getPriority() ? -1 : 1);
  163. });
  164. $this->sortedActions = $actionsClone;
  165. return $this->sortedActions;
  166. }
  167. /**
  168. * Return whether the profile parameter of the target user
  169. * is visible to the visiting user
  170. */
  171. public function isProfileFieldVisible(string $profileField, IUser $targetUser, ?IUser $visitingUser): bool {
  172. try {
  173. $account = $this->accountManager->getAccount($targetUser);
  174. $scope = $account->getProperty($profileField)->getScope();
  175. } catch (PropertyDoesNotExistException $e) {
  176. // Allow the exception as not all profile parameters are account properties
  177. }
  178. $visibility = $this->getProfileConfig($targetUser, $visitingUser)[$profileField]['visibility'];
  179. // Handle profile visibility and account property scope
  180. if ($visibility === self::VISIBILITY_SHOW_USERS_ONLY) {
  181. if (empty($scope)) {
  182. return $visitingUser !== null;
  183. }
  184. return match ($scope) {
  185. IAccountManager::SCOPE_PRIVATE => $visitingUser !== null && $this->knownUserService->isKnownToUser($targetUser->getUID(), $visitingUser->getUID()),
  186. IAccountManager::SCOPE_LOCAL,
  187. IAccountManager::SCOPE_FEDERATED,
  188. IAccountManager::SCOPE_PUBLISHED => $visitingUser !== null,
  189. default => false,
  190. };
  191. }
  192. if ($visibility === self::VISIBILITY_SHOW) {
  193. if (empty($scope)) {
  194. return true;
  195. }
  196. return match ($scope) {
  197. IAccountManager::SCOPE_PRIVATE => $visitingUser !== null && $this->knownUserService->isKnownToUser($targetUser->getUID(), $visitingUser->getUID()),
  198. IAccountManager::SCOPE_LOCAL,
  199. IAccountManager::SCOPE_FEDERATED,
  200. IAccountManager::SCOPE_PUBLISHED => true,
  201. default => false,
  202. };
  203. }
  204. return false;
  205. }
  206. /**
  207. * Return the profile parameters of the target user that are visible to the visiting user
  208. * in an associative array
  209. * @return array{userId: string, address?: string|null, biography?: string|null, displayname?: string|null, headline?: string|null, isUserAvatarVisible?: bool, organisation?: string|null, role?: string|null, actions: list<array{id: string, icon: string, title: string, target: ?string}>}
  210. */
  211. public function getProfileFields(IUser $targetUser, ?IUser $visitingUser): array {
  212. $account = $this->accountManager->getAccount($targetUser);
  213. // Initialize associative array of profile parameters
  214. $profileParameters = [
  215. 'userId' => $account->getUser()->getUID(),
  216. ];
  217. // Add account properties
  218. foreach (self::PROFILE_PROPERTIES as $property) {
  219. switch ($property) {
  220. case IAccountManager::PROPERTY_ADDRESS:
  221. case IAccountManager::PROPERTY_BIOGRAPHY:
  222. case IAccountManager::PROPERTY_DISPLAYNAME:
  223. case IAccountManager::PROPERTY_HEADLINE:
  224. case IAccountManager::PROPERTY_ORGANISATION:
  225. case IAccountManager::PROPERTY_ROLE:
  226. $profileParameters[$property] =
  227. $this->isProfileFieldVisible($property, $targetUser, $visitingUser)
  228. // Explicitly set to null when value is empty string
  229. ? ($account->getProperty($property)->getValue() ?: null)
  230. : null;
  231. break;
  232. case IAccountManager::PROPERTY_AVATAR:
  233. // Add avatar visibility
  234. $profileParameters['isUserAvatarVisible'] = $this->isProfileFieldVisible($property, $targetUser, $visitingUser);
  235. break;
  236. }
  237. }
  238. // Add actions
  239. $profileParameters['actions'] = array_map(
  240. function (ILinkAction $action) {
  241. return [
  242. 'id' => $action->getId(),
  243. 'icon' => $action->getIcon(),
  244. 'title' => $action->getTitle(),
  245. 'target' => $action->getTarget(),
  246. ];
  247. },
  248. // This is needed to reindex the array after filtering
  249. array_values(
  250. array_filter(
  251. $this->getActions($targetUser, $visitingUser),
  252. function (ILinkAction $action) use ($targetUser, $visitingUser) {
  253. return $this->isProfileFieldVisible($action->getId(), $targetUser, $visitingUser);
  254. }
  255. ),
  256. )
  257. );
  258. return $profileParameters;
  259. }
  260. /**
  261. * Return the filtered profile config containing only
  262. * the properties to be stored on the database
  263. */
  264. private function filterNotStoredProfileConfig(array $profileConfig): array {
  265. $dbParamConfigProperties = [
  266. 'visibility',
  267. ];
  268. foreach ($profileConfig as $paramId => $paramConfig) {
  269. $profileConfig[$paramId] = array_intersect_key($paramConfig, array_flip($dbParamConfigProperties));
  270. }
  271. return $profileConfig;
  272. }
  273. /**
  274. * Return the default profile config
  275. */
  276. private function getDefaultProfileConfig(IUser $targetUser, ?IUser $visitingUser): array {
  277. // Construct the default config for actions
  278. $actionsConfig = [];
  279. foreach ($this->getActions($targetUser, $visitingUser) as $action) {
  280. $actionsConfig[$action->getId()] = ['visibility' => self::DEFAULT_VISIBILITY];
  281. }
  282. // Construct the default config for account properties
  283. $propertiesConfig = [];
  284. foreach (self::DEFAULT_PROPERTY_VISIBILITY as $property => $visibility) {
  285. $propertiesConfig[$property] = ['visibility' => $visibility];
  286. }
  287. return array_merge($actionsConfig, $propertiesConfig);
  288. }
  289. /**
  290. * Return the profile config of the target user,
  291. * if a config does not already exist a default config is created and returned
  292. */
  293. public function getProfileConfig(IUser $targetUser, ?IUser $visitingUser): array {
  294. $defaultProfileConfig = $this->getDefaultProfileConfig($targetUser, $visitingUser);
  295. try {
  296. if (($config = $this->configCache[$targetUser->getUID()]) === null) {
  297. $config = $this->configMapper->get($targetUser->getUID());
  298. $this->configCache[$targetUser->getUID()] = $config;
  299. }
  300. // Merge defaults with the existing config in case the defaults are missing
  301. $config->setConfigArray(array_merge(
  302. $defaultProfileConfig,
  303. $this->filterNotStoredProfileConfig($config->getConfigArray()),
  304. ));
  305. $this->configMapper->update($config);
  306. $configArray = $config->getConfigArray();
  307. } catch (DoesNotExistException $e) {
  308. // Create a new default config if it does not exist
  309. $config = new ProfileConfig();
  310. $config->setUserId($targetUser->getUID());
  311. $config->setConfigArray($defaultProfileConfig);
  312. $this->configMapper->insert($config);
  313. $configArray = $config->getConfigArray();
  314. }
  315. return $configArray;
  316. }
  317. /**
  318. * Return the profile config of the target user with additional medatata,
  319. * if a config does not already exist a default config is created and returned
  320. */
  321. public function getProfileConfigWithMetadata(IUser $targetUser, ?IUser $visitingUser): array {
  322. $configArray = $this->getProfileConfig($targetUser, $visitingUser);
  323. $actionsMetadata = [];
  324. foreach ($this->getActions($targetUser, $visitingUser) as $action) {
  325. $actionsMetadata[$action->getId()] = [
  326. 'appId' => $action->getAppId(),
  327. 'displayId' => $action->getDisplayId(),
  328. ];
  329. }
  330. // Add metadata for account property actions which are always configurable
  331. foreach (self::ACCOUNT_PROPERTY_ACTIONS as $actionClass) {
  332. /** @var ILinkAction $action */
  333. $action = $this->container->get($actionClass);
  334. if (!isset($actionsMetadata[$action->getId()])) {
  335. $actionsMetadata[$action->getId()] = [
  336. 'appId' => $action->getAppId(),
  337. 'displayId' => $action->getDisplayId(),
  338. ];
  339. }
  340. }
  341. $propertiesMetadata = [
  342. IAccountManager::PROPERTY_ADDRESS => [
  343. 'appId' => self::CORE_APP_ID,
  344. 'displayId' => $this->l10nFactory->get('lib')->t('Address'),
  345. ],
  346. IAccountManager::PROPERTY_AVATAR => [
  347. 'appId' => self::CORE_APP_ID,
  348. 'displayId' => $this->l10nFactory->get('lib')->t('Profile picture'),
  349. ],
  350. IAccountManager::PROPERTY_BIOGRAPHY => [
  351. 'appId' => self::CORE_APP_ID,
  352. 'displayId' => $this->l10nFactory->get('lib')->t('About'),
  353. ],
  354. IAccountManager::PROPERTY_DISPLAYNAME => [
  355. 'appId' => self::CORE_APP_ID,
  356. 'displayId' => $this->l10nFactory->get('lib')->t('Display name'),
  357. ],
  358. IAccountManager::PROPERTY_HEADLINE => [
  359. 'appId' => self::CORE_APP_ID,
  360. 'displayId' => $this->l10nFactory->get('lib')->t('Headline'),
  361. ],
  362. IAccountManager::PROPERTY_ORGANISATION => [
  363. 'appId' => self::CORE_APP_ID,
  364. 'displayId' => $this->l10nFactory->get('lib')->t('Organisation'),
  365. ],
  366. IAccountManager::PROPERTY_ROLE => [
  367. 'appId' => self::CORE_APP_ID,
  368. 'displayId' => $this->l10nFactory->get('lib')->t('Role'),
  369. ],
  370. ];
  371. $paramMetadata = array_merge($actionsMetadata, $propertiesMetadata);
  372. $configArray = array_intersect_key($configArray, $paramMetadata);
  373. foreach ($configArray as $paramId => $paramConfig) {
  374. if (isset($paramMetadata[$paramId])) {
  375. $configArray[$paramId] = array_merge(
  376. $paramConfig,
  377. $paramMetadata[$paramId],
  378. );
  379. }
  380. }
  381. return $configArray;
  382. }
  383. }