AccountManager.php 23 KB

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