AccountManager.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Accounts;
  8. use Exception;
  9. use InvalidArgumentException;
  10. use OC\Profile\TProfileHelper;
  11. use OCA\Settings\BackgroundJobs\VerifyUserData;
  12. use OCP\Accounts\IAccount;
  13. use OCP\Accounts\IAccountManager;
  14. use OCP\Accounts\IAccountProperty;
  15. use OCP\Accounts\IAccountPropertyCollection;
  16. use OCP\Accounts\PropertyDoesNotExistException;
  17. use OCP\Accounts\UserUpdatedEvent;
  18. use OCP\BackgroundJob\IJobList;
  19. use OCP\Cache\CappedMemoryCache;
  20. use OCP\DB\QueryBuilder\IQueryBuilder;
  21. use OCP\Defaults;
  22. use OCP\EventDispatcher\IEventDispatcher;
  23. use OCP\IConfig;
  24. use OCP\IDBConnection;
  25. use OCP\IL10N;
  26. use OCP\IPhoneNumberUtil;
  27. use OCP\IURLGenerator;
  28. use OCP\IUser;
  29. use OCP\L10N\IFactory;
  30. use OCP\Mail\IMailer;
  31. use OCP\Security\ICrypto;
  32. use OCP\Security\VerificationToken\IVerificationToken;
  33. use OCP\User\Backend\IGetDisplayNameBackend;
  34. use OCP\Util;
  35. use Psr\Log\LoggerInterface;
  36. use function array_flip;
  37. use function iterator_to_array;
  38. use function json_decode;
  39. use function json_encode;
  40. use function json_last_error;
  41. /**
  42. * Class AccountManager
  43. *
  44. * Manage system accounts table
  45. *
  46. * @group DB
  47. * @package OC\Accounts
  48. */
  49. class AccountManager implements IAccountManager {
  50. use TAccountsHelper;
  51. use TProfileHelper;
  52. private string $table = 'accounts';
  53. private string $dataTable = 'accounts_data';
  54. private ?IL10N $l10n = null;
  55. private CappedMemoryCache $internalCache;
  56. /**
  57. * The list of default scopes for each property.
  58. */
  59. public const DEFAULT_SCOPES = [
  60. self::PROPERTY_DISPLAYNAME => self::SCOPE_FEDERATED,
  61. self::PROPERTY_ADDRESS => self::SCOPE_LOCAL,
  62. self::PROPERTY_WEBSITE => self::SCOPE_LOCAL,
  63. self::PROPERTY_EMAIL => self::SCOPE_FEDERATED,
  64. self::PROPERTY_AVATAR => self::SCOPE_FEDERATED,
  65. self::PROPERTY_PHONE => self::SCOPE_LOCAL,
  66. self::PROPERTY_TWITTER => self::SCOPE_LOCAL,
  67. self::PROPERTY_FEDIVERSE => self::SCOPE_LOCAL,
  68. self::PROPERTY_ORGANISATION => self::SCOPE_LOCAL,
  69. self::PROPERTY_ROLE => self::SCOPE_LOCAL,
  70. self::PROPERTY_HEADLINE => self::SCOPE_LOCAL,
  71. self::PROPERTY_BIOGRAPHY => self::SCOPE_LOCAL,
  72. self::PROPERTY_BIRTHDATE => self::SCOPE_LOCAL,
  73. ];
  74. public function __construct(
  75. private IDBConnection $connection,
  76. private IConfig $config,
  77. private IEventDispatcher $dispatcher,
  78. private IJobList $jobList,
  79. private LoggerInterface $logger,
  80. private IVerificationToken $verificationToken,
  81. private IMailer $mailer,
  82. private Defaults $defaults,
  83. private IFactory $l10nFactory,
  84. private IURLGenerator $urlGenerator,
  85. private ICrypto $crypto,
  86. private IPhoneNumberUtil $phoneNumberUtil,
  87. ) {
  88. $this->internalCache = new CappedMemoryCache();
  89. }
  90. /**
  91. * @return string Provided phone number in E.164 format when it was a valid number
  92. * @throws InvalidArgumentException When the phone number was invalid or no default region is set and the number doesn't start with a country code
  93. */
  94. protected function parsePhoneNumber(string $input): string {
  95. $defaultRegion = $this->config->getSystemValueString('default_phone_region', '');
  96. if ($defaultRegion === '') {
  97. // When no default region is set, only +49… numbers are valid
  98. if (!str_starts_with($input, '+')) {
  99. throw new InvalidArgumentException(self::PROPERTY_PHONE);
  100. }
  101. $defaultRegion = 'EN';
  102. }
  103. $phoneNumber = $this->phoneNumberUtil->convertToStandardFormat($input, $defaultRegion);
  104. if ($phoneNumber !== null) {
  105. return $phoneNumber;
  106. }
  107. throw new InvalidArgumentException(self::PROPERTY_PHONE);
  108. }
  109. /**
  110. * @throws InvalidArgumentException When the website did not have http(s) as protocol or the host name was empty
  111. */
  112. protected function parseWebsite(string $input): string {
  113. $parts = parse_url($input);
  114. if (!isset($parts['scheme']) || ($parts['scheme'] !== 'https' && $parts['scheme'] !== 'http')) {
  115. throw new InvalidArgumentException(self::PROPERTY_WEBSITE);
  116. }
  117. if (!isset($parts['host']) || $parts['host'] === '') {
  118. throw new InvalidArgumentException(self::PROPERTY_WEBSITE);
  119. }
  120. return $input;
  121. }
  122. /**
  123. * @param IAccountProperty[] $properties
  124. */
  125. protected function testValueLengths(array $properties, bool $throwOnData = false): void {
  126. foreach ($properties as $property) {
  127. if (strlen($property->getValue()) > 2048) {
  128. if ($throwOnData) {
  129. throw new InvalidArgumentException($property->getName());
  130. } else {
  131. $property->setValue('');
  132. }
  133. }
  134. }
  135. }
  136. protected function testPropertyScope(IAccountProperty $property, array $allowedScopes, bool $throwOnData): void {
  137. if ($throwOnData && !in_array($property->getScope(), $allowedScopes, true)) {
  138. throw new InvalidArgumentException('scope');
  139. }
  140. if (
  141. $property->getScope() === self::SCOPE_PRIVATE
  142. && in_array($property->getName(), [self::PROPERTY_DISPLAYNAME, self::PROPERTY_EMAIL])
  143. ) {
  144. if ($throwOnData) {
  145. // v2-private is not available for these fields
  146. throw new InvalidArgumentException('scope');
  147. } else {
  148. // default to local
  149. $property->setScope(self::SCOPE_LOCAL);
  150. }
  151. } else {
  152. // migrate scope values to the new format
  153. // invalid scopes are mapped to a default value
  154. $property->setScope(AccountProperty::mapScopeToV2($property->getScope()));
  155. }
  156. }
  157. protected function sanitizePhoneNumberValue(IAccountProperty $property, bool $throwOnData = false): void {
  158. if ($property->getName() !== self::PROPERTY_PHONE) {
  159. if ($throwOnData) {
  160. throw new InvalidArgumentException(sprintf('sanitizePhoneNumberValue can only sanitize phone numbers, %s given', $property->getName()));
  161. }
  162. return;
  163. }
  164. if ($property->getValue() === '') {
  165. return;
  166. }
  167. try {
  168. $property->setValue($this->parsePhoneNumber($property->getValue()));
  169. } catch (InvalidArgumentException $e) {
  170. if ($throwOnData) {
  171. throw $e;
  172. }
  173. $property->setValue('');
  174. }
  175. }
  176. protected function sanitizeWebsite(IAccountProperty $property, bool $throwOnData = false): void {
  177. if ($property->getName() !== self::PROPERTY_WEBSITE) {
  178. if ($throwOnData) {
  179. throw new InvalidArgumentException(sprintf('sanitizeWebsite can only sanitize web domains, %s given', $property->getName()));
  180. }
  181. }
  182. try {
  183. $property->setValue($this->parseWebsite($property->getValue()));
  184. } catch (InvalidArgumentException $e) {
  185. if ($throwOnData) {
  186. throw $e;
  187. }
  188. $property->setValue('');
  189. }
  190. }
  191. protected function updateUser(IUser $user, array $data, ?array $oldUserData, bool $throwOnData = false): array {
  192. if ($oldUserData === null) {
  193. $oldUserData = $this->getUser($user, false);
  194. }
  195. $updated = true;
  196. if ($oldUserData !== $data) {
  197. $this->updateExistingUser($user, $data, $oldUserData);
  198. } else {
  199. // nothing needs to be done if new and old data set are the same
  200. $updated = false;
  201. }
  202. if ($updated) {
  203. $this->dispatcher->dispatchTyped(new UserUpdatedEvent(
  204. $user,
  205. $data,
  206. ));
  207. }
  208. return $data;
  209. }
  210. /**
  211. * delete user from accounts table
  212. */
  213. public function deleteUser(IUser $user): void {
  214. $uid = $user->getUID();
  215. $query = $this->connection->getQueryBuilder();
  216. $query->delete($this->table)
  217. ->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
  218. ->execute();
  219. $this->deleteUserData($user);
  220. }
  221. /**
  222. * delete user from accounts table
  223. */
  224. public function deleteUserData(IUser $user): void {
  225. $uid = $user->getUID();
  226. $query = $this->connection->getQueryBuilder();
  227. $query->delete($this->dataTable)
  228. ->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
  229. ->execute();
  230. }
  231. /**
  232. * get stored data from a given user
  233. */
  234. protected function getUser(IUser $user, bool $insertIfNotExists = true): array {
  235. $uid = $user->getUID();
  236. $query = $this->connection->getQueryBuilder();
  237. $query->select('data')
  238. ->from($this->table)
  239. ->where($query->expr()->eq('uid', $query->createParameter('uid')))
  240. ->setParameter('uid', $uid);
  241. $result = $query->executeQuery();
  242. $accountData = $result->fetchAll();
  243. $result->closeCursor();
  244. if (empty($accountData)) {
  245. $userData = $this->buildDefaultUserRecord($user);
  246. if ($insertIfNotExists) {
  247. $this->insertNewUser($user, $userData);
  248. }
  249. return $userData;
  250. }
  251. $userDataArray = $this->importFromJson($accountData[0]['data'], $uid);
  252. if ($userDataArray === null || $userDataArray === []) {
  253. return $this->buildDefaultUserRecord($user);
  254. }
  255. return $this->addMissingDefaultValues($userDataArray, $this->buildDefaultUserRecord($user));
  256. }
  257. public function searchUsers(string $property, array $values): array {
  258. // the value col is limited to 255 bytes. It is used for searches only.
  259. $values = array_map(function (string $value) {
  260. return Util::shortenMultibyteString($value, 255);
  261. }, $values);
  262. $chunks = array_chunk($values, 500);
  263. $query = $this->connection->getQueryBuilder();
  264. $query->select('*')
  265. ->from($this->dataTable)
  266. ->where($query->expr()->eq('name', $query->createNamedParameter($property)))
  267. ->andWhere($query->expr()->in('value', $query->createParameter('values')));
  268. $matches = [];
  269. foreach ($chunks as $chunk) {
  270. $query->setParameter('values', $chunk, IQueryBuilder::PARAM_STR_ARRAY);
  271. $result = $query->executeQuery();
  272. while ($row = $result->fetch()) {
  273. $matches[$row['uid']] = $row['value'];
  274. }
  275. $result->closeCursor();
  276. }
  277. $result = array_merge($matches, $this->searchUsersForRelatedCollection($property, $values));
  278. return array_flip($result);
  279. }
  280. protected function searchUsersForRelatedCollection(string $property, array $values): array {
  281. return match ($property) {
  282. IAccountManager::PROPERTY_EMAIL => array_flip($this->searchUsers(IAccountManager::COLLECTION_EMAIL, $values)),
  283. default => [],
  284. };
  285. }
  286. /**
  287. * check if we need to ask the server for email verification, if yes we create a cronjob
  288. */
  289. protected function checkEmailVerification(IAccount $updatedAccount, array $oldData): void {
  290. try {
  291. $property = $updatedAccount->getProperty(self::PROPERTY_EMAIL);
  292. } catch (PropertyDoesNotExistException $e) {
  293. return;
  294. }
  295. $oldMailIndex = array_search(self::PROPERTY_EMAIL, array_column($oldData, 'name'), true);
  296. $oldMail = $oldMailIndex !== false ? $oldData[$oldMailIndex]['value'] : '';
  297. if ($oldMail !== $property->getValue()) {
  298. $this->jobList->add(
  299. VerifyUserData::class,
  300. [
  301. 'verificationCode' => '',
  302. 'data' => $property->getValue(),
  303. 'type' => self::PROPERTY_EMAIL,
  304. 'uid' => $updatedAccount->getUser()->getUID(),
  305. 'try' => 0,
  306. 'lastRun' => time()
  307. ]
  308. );
  309. $property->setVerified(self::VERIFICATION_IN_PROGRESS);
  310. }
  311. }
  312. protected function checkLocalEmailVerification(IAccount $updatedAccount, array $oldData): void {
  313. $mailCollection = $updatedAccount->getPropertyCollection(self::COLLECTION_EMAIL);
  314. foreach ($mailCollection->getProperties() as $property) {
  315. if ($property->getLocallyVerified() !== self::NOT_VERIFIED) {
  316. continue;
  317. }
  318. if ($this->sendEmailVerificationEmail($updatedAccount->getUser(), $property->getValue())) {
  319. $property->setLocallyVerified(self::VERIFICATION_IN_PROGRESS);
  320. }
  321. }
  322. }
  323. protected function sendEmailVerificationEmail(IUser $user, string $email): bool {
  324. $ref = \substr(hash('sha256', $email), 0, 8);
  325. $key = $this->crypto->encrypt($email);
  326. $token = $this->verificationToken->create($user, 'verifyMail' . $ref, $email);
  327. $link = $this->urlGenerator->linkToRouteAbsolute(
  328. 'provisioning_api.Verification.verifyMail',
  329. [
  330. 'userId' => $user->getUID(),
  331. 'token' => $token,
  332. 'key' => $key
  333. ]
  334. );
  335. $emailTemplate = $this->mailer->createEMailTemplate('core.EmailVerification', [
  336. 'link' => $link,
  337. ]);
  338. if (!$this->l10n) {
  339. $this->l10n = $this->l10nFactory->get('core');
  340. }
  341. $emailTemplate->setSubject($this->l10n->t('%s email verification', [$this->defaults->getName()]));
  342. $emailTemplate->addHeader();
  343. $emailTemplate->addHeading($this->l10n->t('Email verification'));
  344. $emailTemplate->addBodyText(
  345. htmlspecialchars($this->l10n->t('Click the following button to confirm your email.')),
  346. $this->l10n->t('Click the following link to confirm your email.')
  347. );
  348. $emailTemplate->addBodyButton(
  349. htmlspecialchars($this->l10n->t('Confirm your email')),
  350. $link,
  351. false
  352. );
  353. $emailTemplate->addFooter();
  354. try {
  355. $message = $this->mailer->createMessage();
  356. $message->setTo([$email => $user->getDisplayName()]);
  357. $message->setFrom([Util::getDefaultEmailAddress('verification-noreply') => $this->defaults->getName()]);
  358. $message->useTemplate($emailTemplate);
  359. $this->mailer->send($message);
  360. } catch (Exception $e) {
  361. // Log the exception and continue
  362. $this->logger->info('Failed to send verification mail', [
  363. 'app' => 'core',
  364. 'exception' => $e
  365. ]);
  366. return false;
  367. }
  368. return true;
  369. }
  370. /**
  371. * Make sure that all expected data are set
  372. */
  373. protected function addMissingDefaultValues(array $userData, array $defaultUserData): array {
  374. foreach ($defaultUserData as $defaultDataItem) {
  375. // If property does not exist, initialize it
  376. $userDataIndex = array_search($defaultDataItem['name'], array_column($userData, 'name'));
  377. if ($userDataIndex === false) {
  378. $userData[] = $defaultDataItem;
  379. continue;
  380. }
  381. // Merge and extend default missing values
  382. $userData[$userDataIndex] = array_merge($defaultDataItem, $userData[$userDataIndex]);
  383. }
  384. return $userData;
  385. }
  386. protected function updateVerificationStatus(IAccount $updatedAccount, array $oldData): void {
  387. static $propertiesVerifiableByLookupServer = [
  388. self::PROPERTY_TWITTER,
  389. self::PROPERTY_FEDIVERSE,
  390. self::PROPERTY_WEBSITE,
  391. self::PROPERTY_EMAIL,
  392. ];
  393. foreach ($propertiesVerifiableByLookupServer as $propertyName) {
  394. try {
  395. $property = $updatedAccount->getProperty($propertyName);
  396. } catch (PropertyDoesNotExistException $e) {
  397. continue;
  398. }
  399. $wasVerified = isset($oldData[$propertyName])
  400. && isset($oldData[$propertyName]['verified'])
  401. && $oldData[$propertyName]['verified'] === self::VERIFIED;
  402. if ((!isset($oldData[$propertyName])
  403. || !isset($oldData[$propertyName]['value'])
  404. || $property->getValue() !== $oldData[$propertyName]['value'])
  405. && ($property->getVerified() !== self::NOT_VERIFIED
  406. || $wasVerified)
  407. ) {
  408. $property->setVerified(self::NOT_VERIFIED);
  409. }
  410. }
  411. }
  412. /**
  413. * add new user to accounts table
  414. */
  415. protected function insertNewUser(IUser $user, array $data): void {
  416. $uid = $user->getUID();
  417. $jsonEncodedData = $this->prepareJson($data);
  418. $query = $this->connection->getQueryBuilder();
  419. $query->insert($this->table)
  420. ->values(
  421. [
  422. 'uid' => $query->createNamedParameter($uid),
  423. 'data' => $query->createNamedParameter($jsonEncodedData),
  424. ]
  425. )
  426. ->executeStatement();
  427. $this->deleteUserData($user);
  428. $this->writeUserData($user, $data);
  429. }
  430. protected function prepareJson(array $data): string {
  431. $preparedData = [];
  432. foreach ($data as $dataRow) {
  433. $propertyName = $dataRow['name'];
  434. unset($dataRow['name']);
  435. if (isset($dataRow['locallyVerified']) && $dataRow['locallyVerified'] === self::NOT_VERIFIED) {
  436. // do not write default value, save DB space
  437. unset($dataRow['locallyVerified']);
  438. }
  439. if (!$this->isCollection($propertyName)) {
  440. $preparedData[$propertyName] = $dataRow;
  441. continue;
  442. }
  443. if (!isset($preparedData[$propertyName])) {
  444. $preparedData[$propertyName] = [];
  445. }
  446. $preparedData[$propertyName][] = $dataRow;
  447. }
  448. return json_encode($preparedData);
  449. }
  450. protected function importFromJson(string $json, string $userId): ?array {
  451. $result = [];
  452. $jsonArray = json_decode($json, true);
  453. $jsonError = json_last_error();
  454. if ($jsonError !== JSON_ERROR_NONE) {
  455. $this->logger->critical(
  456. 'User data of {uid} contained invalid JSON (error {json_error}), hence falling back to a default user record',
  457. [
  458. 'uid' => $userId,
  459. 'json_error' => $jsonError
  460. ]
  461. );
  462. return null;
  463. }
  464. foreach ($jsonArray as $propertyName => $row) {
  465. if (!$this->isCollection($propertyName)) {
  466. $result[] = array_merge($row, ['name' => $propertyName]);
  467. continue;
  468. }
  469. foreach ($row as $singleRow) {
  470. $result[] = array_merge($singleRow, ['name' => $propertyName]);
  471. }
  472. }
  473. return $result;
  474. }
  475. /**
  476. * Update existing user in accounts table
  477. */
  478. protected function updateExistingUser(IUser $user, array $data, array $oldData): void {
  479. $uid = $user->getUID();
  480. $jsonEncodedData = $this->prepareJson($data);
  481. $query = $this->connection->getQueryBuilder();
  482. $query->update($this->table)
  483. ->set('data', $query->createNamedParameter($jsonEncodedData))
  484. ->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
  485. ->executeStatement();
  486. $this->deleteUserData($user);
  487. $this->writeUserData($user, $data);
  488. }
  489. protected function writeUserData(IUser $user, array $data): void {
  490. $query = $this->connection->getQueryBuilder();
  491. $query->insert($this->dataTable)
  492. ->values(
  493. [
  494. 'uid' => $query->createNamedParameter($user->getUID()),
  495. 'name' => $query->createParameter('name'),
  496. 'value' => $query->createParameter('value'),
  497. ]
  498. );
  499. $this->writeUserDataProperties($query, $data);
  500. }
  501. protected function writeUserDataProperties(IQueryBuilder $query, array $data): void {
  502. foreach ($data as $property) {
  503. if ($property['name'] === self::PROPERTY_AVATAR) {
  504. continue;
  505. }
  506. // the value col is limited to 255 bytes. It is used for searches only.
  507. $value = $property['value'] ? Util::shortenMultibyteString($property['value'], 255) : '';
  508. $query->setParameter('name', $property['name'])
  509. ->setParameter('value', $value);
  510. $query->executeStatement();
  511. }
  512. }
  513. /**
  514. * build default user record in case not data set exists yet
  515. */
  516. protected function buildDefaultUserRecord(IUser $user): array {
  517. $scopes = array_merge(self::DEFAULT_SCOPES, array_filter($this->config->getSystemValue('account_manager.default_property_scope', []), static function (string $scope, string $property) {
  518. return in_array($property, self::ALLOWED_PROPERTIES, true) && in_array($scope, self::ALLOWED_SCOPES, true);
  519. }, ARRAY_FILTER_USE_BOTH));
  520. return [
  521. [
  522. 'name' => self::PROPERTY_DISPLAYNAME,
  523. 'value' => $user->getDisplayName(),
  524. // Display name must be at least SCOPE_LOCAL
  525. 'scope' => $scopes[self::PROPERTY_DISPLAYNAME] === self::SCOPE_PRIVATE ? self::SCOPE_LOCAL : $scopes[self::PROPERTY_DISPLAYNAME],
  526. 'verified' => self::NOT_VERIFIED,
  527. ],
  528. [
  529. 'name' => self::PROPERTY_ADDRESS,
  530. 'value' => '',
  531. 'scope' => $scopes[self::PROPERTY_ADDRESS],
  532. 'verified' => self::NOT_VERIFIED,
  533. ],
  534. [
  535. 'name' => self::PROPERTY_WEBSITE,
  536. 'value' => '',
  537. 'scope' => $scopes[self::PROPERTY_WEBSITE],
  538. 'verified' => self::NOT_VERIFIED,
  539. ],
  540. [
  541. 'name' => self::PROPERTY_EMAIL,
  542. 'value' => $user->getEMailAddress(),
  543. // Email must be at least SCOPE_LOCAL
  544. 'scope' => $scopes[self::PROPERTY_EMAIL] === self::SCOPE_PRIVATE ? self::SCOPE_LOCAL : $scopes[self::PROPERTY_EMAIL],
  545. 'verified' => self::NOT_VERIFIED,
  546. ],
  547. [
  548. 'name' => self::PROPERTY_AVATAR,
  549. 'scope' => $scopes[self::PROPERTY_AVATAR],
  550. ],
  551. [
  552. 'name' => self::PROPERTY_PHONE,
  553. 'value' => '',
  554. 'scope' => $scopes[self::PROPERTY_PHONE],
  555. 'verified' => self::NOT_VERIFIED,
  556. ],
  557. [
  558. 'name' => self::PROPERTY_TWITTER,
  559. 'value' => '',
  560. 'scope' => $scopes[self::PROPERTY_TWITTER],
  561. 'verified' => self::NOT_VERIFIED,
  562. ],
  563. [
  564. 'name' => self::PROPERTY_FEDIVERSE,
  565. 'value' => '',
  566. 'scope' => $scopes[self::PROPERTY_FEDIVERSE],
  567. 'verified' => self::NOT_VERIFIED,
  568. ],
  569. [
  570. 'name' => self::PROPERTY_ORGANISATION,
  571. 'value' => '',
  572. 'scope' => $scopes[self::PROPERTY_ORGANISATION],
  573. ],
  574. [
  575. 'name' => self::PROPERTY_ROLE,
  576. 'value' => '',
  577. 'scope' => $scopes[self::PROPERTY_ROLE],
  578. ],
  579. [
  580. 'name' => self::PROPERTY_HEADLINE,
  581. 'value' => '',
  582. 'scope' => $scopes[self::PROPERTY_HEADLINE],
  583. ],
  584. [
  585. 'name' => self::PROPERTY_BIOGRAPHY,
  586. 'value' => '',
  587. 'scope' => $scopes[self::PROPERTY_BIOGRAPHY],
  588. ],
  589. [
  590. 'name' => self::PROPERTY_BIRTHDATE,
  591. 'value' => '',
  592. 'scope' => $scopes[self::PROPERTY_BIRTHDATE],
  593. ],
  594. [
  595. 'name' => self::PROPERTY_PROFILE_ENABLED,
  596. 'value' => $this->isProfileEnabledByDefault($this->config) ? '1' : '0',
  597. ],
  598. ];
  599. }
  600. private function arrayDataToCollection(IAccount $account, array $data): IAccountPropertyCollection {
  601. $collection = $account->getPropertyCollection($data['name']);
  602. $p = new AccountProperty(
  603. $data['name'],
  604. $data['value'] ?? '',
  605. $data['scope'] ?? self::SCOPE_LOCAL,
  606. $data['verified'] ?? self::NOT_VERIFIED,
  607. ''
  608. );
  609. $p->setLocallyVerified($data['locallyVerified'] ?? self::NOT_VERIFIED);
  610. $collection->addProperty($p);
  611. return $collection;
  612. }
  613. private function parseAccountData(IUser $user, $data): Account {
  614. $account = new Account($user);
  615. foreach ($data as $accountData) {
  616. if ($this->isCollection($accountData['name'])) {
  617. $account->setPropertyCollection($this->arrayDataToCollection($account, $accountData));
  618. } else {
  619. $account->setProperty($accountData['name'], $accountData['value'] ?? '', $accountData['scope'] ?? self::SCOPE_LOCAL, $accountData['verified'] ?? self::NOT_VERIFIED);
  620. if (isset($accountData['locallyVerified'])) {
  621. $property = $account->getProperty($accountData['name']);
  622. $property->setLocallyVerified($accountData['locallyVerified']);
  623. }
  624. }
  625. }
  626. return $account;
  627. }
  628. public function getAccount(IUser $user): IAccount {
  629. $cached = $this->internalCache->get($user->getUID());
  630. if ($cached !== null) {
  631. return $cached;
  632. }
  633. $account = $this->parseAccountData($user, $this->getUser($user));
  634. if ($user->getBackend() instanceof IGetDisplayNameBackend) {
  635. $property = $account->getProperty(self::PROPERTY_DISPLAYNAME);
  636. $account->setProperty(self::PROPERTY_DISPLAYNAME, $user->getDisplayName(), $property->getScope(), $property->getVerified());
  637. }
  638. $this->internalCache->set($user->getUID(), $account);
  639. return $account;
  640. }
  641. public function updateAccount(IAccount $account): void {
  642. $this->testValueLengths(iterator_to_array($account->getAllProperties()), true);
  643. try {
  644. $property = $account->getProperty(self::PROPERTY_PHONE);
  645. $this->sanitizePhoneNumberValue($property);
  646. } catch (PropertyDoesNotExistException $e) {
  647. // valid case, nothing to do
  648. }
  649. try {
  650. $property = $account->getProperty(self::PROPERTY_WEBSITE);
  651. $this->sanitizeWebsite($property);
  652. } catch (PropertyDoesNotExistException $e) {
  653. // valid case, nothing to do
  654. }
  655. foreach ($account->getAllProperties() as $property) {
  656. $this->testPropertyScope($property, self::ALLOWED_SCOPES, true);
  657. }
  658. $oldData = $this->getUser($account->getUser(), false);
  659. $this->updateVerificationStatus($account, $oldData);
  660. $this->checkEmailVerification($account, $oldData);
  661. $this->checkLocalEmailVerification($account, $oldData);
  662. $data = [];
  663. foreach ($account->getAllProperties() as $property) {
  664. /** @var IAccountProperty $property */
  665. $data[] = [
  666. 'name' => $property->getName(),
  667. 'value' => $property->getValue(),
  668. 'scope' => $property->getScope(),
  669. 'verified' => $property->getVerified(),
  670. 'locallyVerified' => $property->getLocallyVerified(),
  671. ];
  672. }
  673. $this->updateUser($account->getUser(), $data, $oldData, true);
  674. $this->internalCache->set($account->getUser()->getUID(), $account);
  675. }
  676. }