AccountManager.php 25 KB

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