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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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\IUser;
  40. use OCP\L10N\IFactory;
  41. use OCP\Profile\ILinkAction;
  42. use Psr\Container\ContainerInterface;
  43. use Psr\Log\LoggerInterface;
  44. class ProfileManager {
  45. /** @var IAccountManager */
  46. private $accountManager;
  47. /** @var IAppManager */
  48. private $appManager;
  49. /** @var ProfileConfigMapper */
  50. private $configMapper;
  51. /** @var ContainerInterface */
  52. private $container;
  53. /** @var KnownUserService */
  54. private $knownUserService;
  55. /** @var IFactory */
  56. private $l10nFactory;
  57. /** @var LoggerInterface */
  58. private $logger;
  59. /** @var Coordinator */
  60. private $coordinator;
  61. /** @var ILinkAction[] */
  62. private $actions = [];
  63. /** @var null|ILinkAction[] */
  64. private $sortedActions = null;
  65. private const CORE_APP_ID = 'core';
  66. /**
  67. * Array of account property actions
  68. */
  69. private const ACCOUNT_PROPERTY_ACTIONS = [
  70. EmailAction::class,
  71. PhoneAction::class,
  72. WebsiteAction::class,
  73. TwitterAction::class,
  74. ];
  75. /**
  76. * Array of account properties displayed on the profile
  77. */
  78. private const PROFILE_PROPERTIES = [
  79. IAccountManager::PROPERTY_ADDRESS,
  80. IAccountManager::PROPERTY_AVATAR,
  81. IAccountManager::PROPERTY_BIOGRAPHY,
  82. IAccountManager::PROPERTY_DISPLAYNAME,
  83. IAccountManager::PROPERTY_HEADLINE,
  84. IAccountManager::PROPERTY_ORGANISATION,
  85. IAccountManager::PROPERTY_ROLE,
  86. ];
  87. public function __construct(
  88. IAccountManager $accountManager,
  89. IAppManager $appManager,
  90. ProfileConfigMapper $configMapper,
  91. ContainerInterface $container,
  92. KnownUserService $knownUserService,
  93. IFactory $l10nFactory,
  94. LoggerInterface $logger,
  95. Coordinator $coordinator
  96. ) {
  97. $this->accountManager = $accountManager;
  98. $this->appManager = $appManager;
  99. $this->configMapper = $configMapper;
  100. $this->container = $container;
  101. $this->knownUserService = $knownUserService;
  102. $this->l10nFactory = $l10nFactory;
  103. $this->logger = $logger;
  104. $this->coordinator = $coordinator;
  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->getUID());
  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. private function isParameterVisible(string $paramId, IUser $targetUser, ?IUser $visitingUser): bool {
  172. try {
  173. $account = $this->accountManager->getAccount($targetUser);
  174. $scope = $account->getProperty($paramId)->getScope();
  175. } catch (PropertyDoesNotExistException $e) {
  176. // Allow the exception as not all profile parameters are account properties
  177. }
  178. $visibility = $this->getProfileConfig($targetUser, $visitingUser)[$paramId]['visibility'];
  179. // Handle profile visibility and account property scope
  180. switch ($visibility) {
  181. case ProfileConfig::VISIBILITY_HIDE:
  182. return false;
  183. case ProfileConfig::VISIBILITY_SHOW_USERS_ONLY:
  184. if (!empty($scope)) {
  185. switch ($scope) {
  186. case IAccountManager::SCOPE_PRIVATE:
  187. return $visitingUser !== null && $this->knownUserService->isKnownToUser($targetUser->getUID(), $visitingUser->getUID());
  188. case IAccountManager::SCOPE_LOCAL:
  189. case IAccountManager::SCOPE_FEDERATED:
  190. case IAccountManager::SCOPE_PUBLISHED:
  191. return $visitingUser !== null;
  192. default:
  193. return false;
  194. }
  195. }
  196. return $visitingUser !== null;
  197. case ProfileConfig::VISIBILITY_SHOW:
  198. if (!empty($scope)) {
  199. switch ($scope) {
  200. case IAccountManager::SCOPE_PRIVATE:
  201. return $visitingUser !== null && $this->knownUserService->isKnownToUser($targetUser->getUID(), $visitingUser->getUID());
  202. case IAccountManager::SCOPE_LOCAL:
  203. case IAccountManager::SCOPE_FEDERATED:
  204. case IAccountManager::SCOPE_PUBLISHED:
  205. return true;
  206. default:
  207. return false;
  208. }
  209. }
  210. return true;
  211. default:
  212. return false;
  213. }
  214. }
  215. /**
  216. * Return the profile parameters of the target user that are visible to the visiting user
  217. * in an associative array
  218. */
  219. public function getProfileParams(IUser $targetUser, ?IUser $visitingUser): array {
  220. $account = $this->accountManager->getAccount($targetUser);
  221. // Initialize associative array of profile parameters
  222. $profileParameters = [
  223. 'userId' => $account->getUser()->getUID(),
  224. ];
  225. // Add account properties
  226. foreach (self::PROFILE_PROPERTIES as $property) {
  227. switch ($property) {
  228. case IAccountManager::PROPERTY_ADDRESS:
  229. case IAccountManager::PROPERTY_BIOGRAPHY:
  230. case IAccountManager::PROPERTY_DISPLAYNAME:
  231. case IAccountManager::PROPERTY_HEADLINE:
  232. case IAccountManager::PROPERTY_ORGANISATION:
  233. case IAccountManager::PROPERTY_ROLE:
  234. $profileParameters[$property] =
  235. $this->isParameterVisible($property, $targetUser, $visitingUser)
  236. // Explicitly set to null when value is empty string
  237. ? ($account->getProperty($property)->getValue() ?: null)
  238. : null;
  239. break;
  240. case IAccountManager::PROPERTY_AVATAR:
  241. // Add avatar visibility
  242. $profileParameters['isUserAvatarVisible'] = $this->isParameterVisible($property, $targetUser, $visitingUser);
  243. break;
  244. }
  245. }
  246. // Add actions
  247. $profileParameters['actions'] = array_map(
  248. function (ILinkAction $action) {
  249. return [
  250. 'id' => $action->getId(),
  251. 'icon' => $action->getIcon(),
  252. 'title' => $action->getTitle(),
  253. 'target' => $action->getTarget(),
  254. ];
  255. },
  256. // This is needed to reindex the array after filtering
  257. array_values(
  258. array_filter(
  259. $this->getActions($targetUser, $visitingUser),
  260. function (ILinkAction $action) use ($targetUser, $visitingUser) {
  261. return $this->isParameterVisible($action->getId(), $targetUser, $visitingUser);
  262. }
  263. ),
  264. )
  265. );
  266. return $profileParameters;
  267. }
  268. /**
  269. * Return the filtered profile config containing only
  270. * the properties to be stored on the database
  271. */
  272. private function filterNotStoredProfileConfig(array $profileConfig): array {
  273. $dbParamConfigProperties = [
  274. 'visibility',
  275. ];
  276. foreach ($profileConfig as $paramId => $paramConfig) {
  277. $profileConfig[$paramId] = array_intersect_key($paramConfig, array_flip($dbParamConfigProperties));
  278. }
  279. return $profileConfig;
  280. }
  281. /**
  282. * Return the default profile config
  283. */
  284. private function getDefaultProfileConfig(IUser $targetUser, ?IUser $visitingUser): array {
  285. // Contruct the default config for actions
  286. $actionsConfig = [];
  287. foreach ($this->getActions($targetUser, $visitingUser) as $action) {
  288. $actionsConfig[$action->getId()] = ['visibility' => ProfileConfig::DEFAULT_VISIBILITY];
  289. }
  290. // Contruct the default config for account properties
  291. $propertiesConfig = [];
  292. foreach (ProfileConfig::DEFAULT_PROPERTY_VISIBILITY as $property => $visibility) {
  293. $propertiesConfig[$property] = ['visibility' => $visibility];
  294. }
  295. return array_merge($actionsConfig, $propertiesConfig);
  296. }
  297. /**
  298. * Return the profile config of the target user,
  299. * if a config does not already exist a default config is created and returned
  300. */
  301. public function getProfileConfig(IUser $targetUser, ?IUser $visitingUser): array {
  302. $defaultProfileConfig = $this->getDefaultProfileConfig($targetUser, $visitingUser);
  303. try {
  304. $config = $this->configMapper->get($targetUser->getUID());
  305. // Merge defaults with the existing config in case the defaults are missing
  306. $config->setConfigArray(array_merge(
  307. $defaultProfileConfig,
  308. $this->filterNotStoredProfileConfig($config->getConfigArray()),
  309. ));
  310. $this->configMapper->update($config);
  311. $configArray = $config->getConfigArray();
  312. } catch (DoesNotExistException $e) {
  313. // Create a new default config if it does not exist
  314. $config = new ProfileConfig();
  315. $config->setUserId($targetUser->getUID());
  316. $config->setConfigArray($defaultProfileConfig);
  317. $this->configMapper->insert($config);
  318. $configArray = $config->getConfigArray();
  319. }
  320. return $configArray;
  321. }
  322. /**
  323. * Return the profile config of the target user with additional medatata,
  324. * if a config does not already exist a default config is created and returned
  325. */
  326. public function getProfileConfigWithMetadata(IUser $targetUser, ?IUser $visitingUser): array {
  327. $configArray = $this->getProfileConfig($targetUser, $visitingUser);
  328. $actionsMetadata = [];
  329. foreach ($this->getActions($targetUser, $visitingUser) as $action) {
  330. $actionsMetadata[$action->getId()] = [
  331. 'appId' => $action->getAppId(),
  332. 'displayId' => $action->getDisplayId(),
  333. ];
  334. }
  335. // Add metadata for account property actions which are always configurable
  336. foreach (self::ACCOUNT_PROPERTY_ACTIONS as $actionClass) {
  337. /** @var ILinkAction $action */
  338. $action = $this->container->get($actionClass);
  339. if (!isset($actionsMetadata[$action->getId()])) {
  340. $actionsMetadata[$action->getId()] = [
  341. 'appId' => $action->getAppId(),
  342. 'displayId' => $action->getDisplayId(),
  343. ];
  344. }
  345. }
  346. $propertiesMetadata = [
  347. IAccountManager::PROPERTY_ADDRESS => [
  348. 'appId' => self::CORE_APP_ID,
  349. 'displayId' => $this->l10nFactory->get('lib')->t('Address'),
  350. ],
  351. IAccountManager::PROPERTY_AVATAR => [
  352. 'appId' => self::CORE_APP_ID,
  353. 'displayId' => $this->l10nFactory->get('lib')->t('Profile picture'),
  354. ],
  355. IAccountManager::PROPERTY_BIOGRAPHY => [
  356. 'appId' => self::CORE_APP_ID,
  357. 'displayId' => $this->l10nFactory->get('lib')->t('About'),
  358. ],
  359. IAccountManager::PROPERTY_DISPLAYNAME => [
  360. 'appId' => self::CORE_APP_ID,
  361. 'displayId' => $this->l10nFactory->get('lib')->t('Full name'),
  362. ],
  363. IAccountManager::PROPERTY_HEADLINE => [
  364. 'appId' => self::CORE_APP_ID,
  365. 'displayId' => $this->l10nFactory->get('lib')->t('Headline'),
  366. ],
  367. IAccountManager::PROPERTY_ORGANISATION => [
  368. 'appId' => self::CORE_APP_ID,
  369. 'displayId' => $this->l10nFactory->get('lib')->t('Organisation'),
  370. ],
  371. IAccountManager::PROPERTY_ROLE => [
  372. 'appId' => self::CORE_APP_ID,
  373. 'displayId' => $this->l10nFactory->get('lib')->t('Role'),
  374. ],
  375. ];
  376. $paramMetadata = array_merge($actionsMetadata, $propertiesMetadata);
  377. $configArray = array_intersect_key($configArray, $paramMetadata);
  378. foreach ($configArray as $paramId => $paramConfig) {
  379. if (isset($paramMetadata[$paramId])) {
  380. $configArray[$paramId] = array_merge(
  381. $paramConfig,
  382. $paramMetadata[$paramId],
  383. );
  384. }
  385. }
  386. return $configArray;
  387. }
  388. }