You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AccountManager.php 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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 OC\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_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 (strpos($input, '+') !== 0) {
  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 ($phoneNumber instanceof PhoneNumber && $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();
  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_WEBSITE,
  467. self::PROPERTY_EMAIL,
  468. ];
  469. foreach ($propertiesVerifiableByLookupServer as $propertyName) {
  470. try {
  471. $property = $updatedAccount->getProperty($propertyName);
  472. } catch (PropertyDoesNotExistException $e) {
  473. continue;
  474. }
  475. $wasVerified = isset($oldData[$propertyName])
  476. && isset($oldData[$propertyName]['verified'])
  477. && $oldData[$propertyName]['verified'] === self::VERIFIED;
  478. if ((!isset($oldData[$propertyName])
  479. || !isset($oldData[$propertyName]['value'])
  480. || $property->getValue() !== $oldData[$propertyName]['value'])
  481. && ($property->getVerified() !== self::NOT_VERIFIED
  482. || $wasVerified)
  483. ) {
  484. $property->setVerified(self::NOT_VERIFIED);
  485. }
  486. }
  487. }
  488. /**
  489. * add new user to accounts table
  490. *
  491. * @param IUser $user
  492. * @param array $data
  493. */
  494. protected function insertNewUser(IUser $user, array $data): void {
  495. $uid = $user->getUID();
  496. $jsonEncodedData = $this->prepareJson($data);
  497. $query = $this->connection->getQueryBuilder();
  498. $query->insert($this->table)
  499. ->values(
  500. [
  501. 'uid' => $query->createNamedParameter($uid),
  502. 'data' => $query->createNamedParameter($jsonEncodedData),
  503. ]
  504. )
  505. ->executeStatement();
  506. $this->deleteUserData($user);
  507. $this->writeUserData($user, $data);
  508. }
  509. protected function prepareJson(array $data): string {
  510. $preparedData = [];
  511. foreach ($data as $dataRow) {
  512. $propertyName = $dataRow['name'];
  513. unset($dataRow['name']);
  514. if (isset($dataRow['locallyVerified']) && $dataRow['locallyVerified'] === self::NOT_VERIFIED) {
  515. // do not write default value, save DB space
  516. unset($dataRow['locallyVerified']);
  517. }
  518. if (!$this->isCollection($propertyName)) {
  519. $preparedData[$propertyName] = $dataRow;
  520. continue;
  521. }
  522. if (!isset($preparedData[$propertyName])) {
  523. $preparedData[$propertyName] = [];
  524. }
  525. $preparedData[$propertyName][] = $dataRow;
  526. }
  527. return json_encode($preparedData);
  528. }
  529. protected function importFromJson(string $json, string $userId): ?array {
  530. $result = [];
  531. $jsonArray = json_decode($json, true);
  532. $jsonError = json_last_error();
  533. if ($jsonError !== JSON_ERROR_NONE) {
  534. $this->logger->critical(
  535. 'User data of {uid} contained invalid JSON (error {json_error}), hence falling back to a default user record',
  536. [
  537. 'uid' => $userId,
  538. 'json_error' => $jsonError
  539. ]
  540. );
  541. return null;
  542. }
  543. foreach ($jsonArray as $propertyName => $row) {
  544. if (!$this->isCollection($propertyName)) {
  545. $result[] = array_merge($row, ['name' => $propertyName]);
  546. continue;
  547. }
  548. foreach ($row as $singleRow) {
  549. $result[] = array_merge($singleRow, ['name' => $propertyName]);
  550. }
  551. }
  552. return $result;
  553. }
  554. /**
  555. * Update existing user in accounts table
  556. */
  557. protected function updateExistingUser(IUser $user, array $data, array $oldData): void {
  558. $uid = $user->getUID();
  559. $jsonEncodedData = $this->prepareJson($data);
  560. $query = $this->connection->getQueryBuilder();
  561. $query->update($this->table)
  562. ->set('data', $query->createNamedParameter($jsonEncodedData))
  563. ->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
  564. ->executeStatement();
  565. $this->deleteUserData($user);
  566. $this->writeUserData($user, $data);
  567. }
  568. protected function writeUserData(IUser $user, array $data): void {
  569. $query = $this->connection->getQueryBuilder();
  570. $query->insert($this->dataTable)
  571. ->values(
  572. [
  573. 'uid' => $query->createNamedParameter($user->getUID()),
  574. 'name' => $query->createParameter('name'),
  575. 'value' => $query->createParameter('value'),
  576. ]
  577. );
  578. $this->writeUserDataProperties($query, $data);
  579. }
  580. protected function writeUserDataProperties(IQueryBuilder $query, array $data): void {
  581. foreach ($data as $property) {
  582. if ($property['name'] === self::PROPERTY_AVATAR) {
  583. continue;
  584. }
  585. // the value col is limited to 255 bytes. It is used for searches only.
  586. $value = $property['value'] ? Util::shortenMultibyteString($property['value'], 255) : '';
  587. $query->setParameter('name', $property['name'])
  588. ->setParameter('value', $value);
  589. $query->executeStatement();
  590. }
  591. }
  592. /**
  593. * build default user record in case not data set exists yet
  594. */
  595. protected function buildDefaultUserRecord(IUser $user): array {
  596. $scopes = array_merge(self::DEFAULT_SCOPES, array_filter($this->config->getSystemValue('account_manager.default_property_scope', []), static function (string $scope, string $property) {
  597. return in_array($property, self::ALLOWED_PROPERTIES, true) && in_array($scope, self::ALLOWED_SCOPES, true);
  598. }, ARRAY_FILTER_USE_BOTH));
  599. return [
  600. [
  601. 'name' => self::PROPERTY_DISPLAYNAME,
  602. 'value' => $user->getDisplayName(),
  603. // Display name must be at least SCOPE_LOCAL
  604. 'scope' => $scopes[self::PROPERTY_DISPLAYNAME] === self::SCOPE_PRIVATE ? self::SCOPE_LOCAL : $scopes[self::PROPERTY_DISPLAYNAME],
  605. 'verified' => self::NOT_VERIFIED,
  606. ],
  607. [
  608. 'name' => self::PROPERTY_ADDRESS,
  609. 'value' => '',
  610. 'scope' => $scopes[self::PROPERTY_ADDRESS],
  611. 'verified' => self::NOT_VERIFIED,
  612. ],
  613. [
  614. 'name' => self::PROPERTY_WEBSITE,
  615. 'value' => '',
  616. 'scope' => $scopes[self::PROPERTY_WEBSITE],
  617. 'verified' => self::NOT_VERIFIED,
  618. ],
  619. [
  620. 'name' => self::PROPERTY_EMAIL,
  621. 'value' => $user->getEMailAddress(),
  622. // Email must be at least SCOPE_LOCAL
  623. 'scope' => $scopes[self::PROPERTY_EMAIL] === self::SCOPE_PRIVATE ? self::SCOPE_LOCAL : $scopes[self::PROPERTY_EMAIL],
  624. 'verified' => self::NOT_VERIFIED,
  625. ],
  626. [
  627. 'name' => self::PROPERTY_AVATAR,
  628. 'scope' => $scopes[self::PROPERTY_AVATAR],
  629. ],
  630. [
  631. 'name' => self::PROPERTY_PHONE,
  632. 'value' => '',
  633. 'scope' => $scopes[self::PROPERTY_PHONE],
  634. 'verified' => self::NOT_VERIFIED,
  635. ],
  636. [
  637. 'name' => self::PROPERTY_TWITTER,
  638. 'value' => '',
  639. 'scope' => $scopes[self::PROPERTY_TWITTER],
  640. 'verified' => self::NOT_VERIFIED,
  641. ],
  642. [
  643. 'name' => self::PROPERTY_ORGANISATION,
  644. 'value' => '',
  645. 'scope' => $scopes[self::PROPERTY_ORGANISATION],
  646. ],
  647. [
  648. 'name' => self::PROPERTY_ROLE,
  649. 'value' => '',
  650. 'scope' => $scopes[self::PROPERTY_ROLE],
  651. ],
  652. [
  653. 'name' => self::PROPERTY_HEADLINE,
  654. 'value' => '',
  655. 'scope' => $scopes[self::PROPERTY_HEADLINE],
  656. ],
  657. [
  658. 'name' => self::PROPERTY_BIOGRAPHY,
  659. 'value' => '',
  660. 'scope' => $scopes[self::PROPERTY_BIOGRAPHY],
  661. ],
  662. [
  663. 'name' => self::PROPERTY_PROFILE_ENABLED,
  664. 'value' => $this->isProfileEnabledByDefault($this->config) ? '1' : '0',
  665. ],
  666. ];
  667. }
  668. private function arrayDataToCollection(IAccount $account, array $data): IAccountPropertyCollection {
  669. $collection = $account->getPropertyCollection($data['name']);
  670. $p = new AccountProperty(
  671. $data['name'],
  672. $data['value'] ?? '',
  673. $data['scope'] ?? self::SCOPE_LOCAL,
  674. $data['verified'] ?? self::NOT_VERIFIED,
  675. ''
  676. );
  677. $p->setLocallyVerified($data['locallyVerified'] ?? self::NOT_VERIFIED);
  678. $collection->addProperty($p);
  679. return $collection;
  680. }
  681. private function parseAccountData(IUser $user, $data): Account {
  682. $account = new Account($user);
  683. foreach ($data as $accountData) {
  684. if ($this->isCollection($accountData['name'])) {
  685. $account->setPropertyCollection($this->arrayDataToCollection($account, $accountData));
  686. } else {
  687. $account->setProperty($accountData['name'], $accountData['value'] ?? '', $accountData['scope'] ?? self::SCOPE_LOCAL, $accountData['verified'] ?? self::NOT_VERIFIED);
  688. if (isset($accountData['locallyVerified'])) {
  689. $property = $account->getProperty($accountData['name']);
  690. $property->setLocallyVerified($accountData['locallyVerified']);
  691. }
  692. }
  693. }
  694. return $account;
  695. }
  696. public function getAccount(IUser $user): IAccount {
  697. if ($this->internalCache->hasKey($user->getUID())) {
  698. return $this->internalCache->get($user->getUID());
  699. }
  700. $account = $this->parseAccountData($user, $this->getUser($user));
  701. $this->internalCache->set($user->getUID(), $account);
  702. return $account;
  703. }
  704. public function updateAccount(IAccount $account): void {
  705. $this->testValueLengths(iterator_to_array($account->getAllProperties()), true);
  706. try {
  707. $property = $account->getProperty(self::PROPERTY_PHONE);
  708. $this->sanitizePhoneNumberValue($property);
  709. } catch (PropertyDoesNotExistException $e) {
  710. // valid case, nothing to do
  711. }
  712. try {
  713. $property = $account->getProperty(self::PROPERTY_WEBSITE);
  714. $this->sanitizeWebsite($property);
  715. } catch (PropertyDoesNotExistException $e) {
  716. // valid case, nothing to do
  717. }
  718. foreach ($account->getAllProperties() as $property) {
  719. $this->testPropertyScope($property, self::ALLOWED_SCOPES, true);
  720. }
  721. $oldData = $this->getUser($account->getUser(), false);
  722. $this->updateVerificationStatus($account, $oldData);
  723. $this->checkEmailVerification($account, $oldData);
  724. $this->checkLocalEmailVerification($account, $oldData);
  725. $data = [];
  726. foreach ($account->getAllProperties() as $property) {
  727. /** @var IAccountProperty $property */
  728. $data[] = [
  729. 'name' => $property->getName(),
  730. 'value' => $property->getValue(),
  731. 'scope' => $property->getScope(),
  732. 'verified' => $property->getVerified(),
  733. 'locallyVerified' => $property->getLocallyVerified(),
  734. ];
  735. }
  736. $this->updateUser($account->getUser(), $data, $oldData, true);
  737. $this->internalCache->set($account->getUser()->getUID(), $account);
  738. }
  739. }