AccountManager.php 25 KB

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