AccountManager.php 23 KB

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