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