1
0

AccountManager.php 24 KB

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