AccountManager.php 25 KB

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