ProfileManager.php 15 KB

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