summaryrefslogtreecommitdiffstats
path: root/lib/private/Accounts/AccountManager.php
blob: a3f971df6a118ac3c78eaf36408eedaf6291bbd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
<?php
/**
 * @copyright Copyright (c) 2016, ownCloud, Inc.
 * @copyright Copyright (c) 2016, Björn Schießle
 *
 * @author Bjoern Schiessle <bjoern@schiessle.org>
 * @author Björn Schießle <bjoern@schiessle.org>
 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
 * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
 * @author Daniel Kesselberg <mail@danielkesselberg.de>
 * @author Joas Schilling <coding@schilljs.com>
 * @author Julius Härtl <jus@bitgrid.net>
 * @author Lukas Reschke <lukas@statuscode.ch>
 * @author Morris Jobke <hey@morrisjobke.de>
 * @author Roeland Jago Douma <roeland@famdouma.nl>
 * @author Vincent Petry <vincent@nextcloud.com>
 *
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 *
 */
namespace OC\Accounts;

use Exception;
use InvalidArgumentException;
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;
use OCA\Settings\BackgroundJobs\VerifyUserData;
use OCP\Accounts\IAccount;
use OCP\Accounts\IAccountManager;
use OCP\Accounts\IAccountProperty;
use OCP\Accounts\IAccountPropertyCollection;
use OCP\Accounts\PropertyDoesNotExistException;
use OCP\BackgroundJob\IJobList;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Defaults;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\L10N\IFactory;
use OCP\Mail\IMailer;
use OCP\Security\ICrypto;
use OCP\Security\VerificationToken\IVerificationToken;
use OCP\Util;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use function array_flip;
use function iterator_to_array;
use function json_decode;
use function json_encode;
use function json_last_error;

/**
 * Class AccountManager
 *
 * Manage system accounts table
 *
 * @group DB
 * @package OC\Accounts
 */
class AccountManager implements IAccountManager {
	use TAccountsHelper;

	/** @var  IDBConnection database connection */
	private $connection;

	/** @var IConfig */
	private $config;

	/** @var string table name */
	private $table = 'accounts';

	/** @var string table name */
	private $dataTable = 'accounts_data';

	/** @var EventDispatcherInterface */
	private $eventDispatcher;

	/** @var IJobList */
	private $jobList;

	/** @var LoggerInterface */
	private $logger;
	/** @var IVerificationToken */
	private $verificationToken;
	/** @var IMailer */
	private $mailer;
	/** @var Defaults */
	private $defaults;
	/** @var IL10N */
	private $l10n;
	/** @var IURLGenerator */
	private $urlGenerator;
	/** @var ICrypto */
	private $crypto;
	/** @var IFactory */
	private $l10nfactory;

	public function __construct(
		IDBConnection            $connection,
		IConfig                  $config,
		EventDispatcherInterface $eventDispatcher,
		IJobList                 $jobList,
		LoggerInterface          $logger,
		IVerificationToken       $verificationToken,
		IMailer                  $mailer,
		Defaults                 $defaults,
		IFactory                 $factory,
		IURLGenerator            $urlGenerator,
		ICrypto                  $crypto
	) {
		$this->connection = $connection;
		$this->config = $config;
		$this->eventDispatcher = $eventDispatcher;
		$this->jobList = $jobList;
		$this->logger = $logger;
		$this->verificationToken = $verificationToken;
		$this->mailer = $mailer;
		$this->defaults = $defaults;
		$this->urlGenerator = $urlGenerator;
		$this->crypto = $crypto;
		// DIing IL10N results in a dependency loop
		$this->l10nfactory = $factory;
	}

	/**
	 * @param string $input
	 * @return string Provided phone number in E.164 format when it was a valid number
	 * @throws InvalidArgumentException When the phone number was invalid or no default region is set and the number doesn't start with a country code
	 */
	protected function parsePhoneNumber(string $input): string {
		$defaultRegion = $this->config->getSystemValueString('default_phone_region', '');

		if ($defaultRegion === '') {
			// When no default region is set, only +49… numbers are valid
			if (strpos($input, '+') !== 0) {
				throw new InvalidArgumentException(self::PROPERTY_PHONE);
			}

			$defaultRegion = 'EN';
		}

		$phoneUtil = PhoneNumberUtil::getInstance();
		try {
			$phoneNumber = $phoneUtil->parse($input, $defaultRegion);
			if ($phoneNumber instanceof PhoneNumber && $phoneUtil->isValidNumber($phoneNumber)) {
				return $phoneUtil->format($phoneNumber, PhoneNumberFormat::E164);
			}
		} catch (NumberParseException $e) {
		}

		throw new InvalidArgumentException(self::PROPERTY_PHONE);
	}

	/**
	 *
	 * @param string $input
	 * @return string
	 * @throws InvalidArgumentException When the website did not have http(s) as protocol or the host name was empty
	 */
	protected function parseWebsite(string $input): string {
		$parts = parse_url($input);
		if (!isset($parts['scheme']) || ($parts['scheme'] !== 'https' && $parts['scheme'] !== 'http')) {
			throw new InvalidArgumentException(self::PROPERTY_WEBSITE);
		}

		if (!isset($parts['host']) || $parts['host'] === '') {
			throw new InvalidArgumentException(self::PROPERTY_WEBSITE);
		}

		return $input;
	}

	/**
	 * @param IAccountProperty[] $properties
	 */
	protected function testValueLengths(array $properties, bool $throwOnData = false): void {
		foreach ($properties as $property) {
			if (strlen($property->getValue()) > 2048) {
				if ($throwOnData) {
					throw new InvalidArgumentException();
				} else {
					$property->setValue('');
				}
			}
		}
	}

	protected function testPropertyScope(IAccountProperty $property, array $allowedScopes, bool $throwOnData): void {
		if ($throwOnData && !in_array($property->getScope(), $allowedScopes, true)) {
			throw new InvalidArgumentException('scope');
		}

		if (
			$property->getScope() === self::SCOPE_PRIVATE
			&& in_array($property->getName(), [self::PROPERTY_DISPLAYNAME, self::PROPERTY_EMAIL])
		) {
			if ($throwOnData) {
				// v2-private is not available for these fields
				throw new InvalidArgumentException('scope');
			} else {
				// default to local
				$property->setScope(self::SCOPE_LOCAL);
			}
		} else {
			// migrate scope values to the new format
			// invalid scopes are mapped to a default value
			$property->setScope(AccountProperty::mapScopeToV2($property->getScope()));
		}
	}

	protected function sanitizePhoneNumberValue(IAccountProperty $property, bool $throwOnData = false) {
		if ($property->getName() !== self::PROPERTY_PHONE) {
			if ($throwOnData) {
				throw new InvalidArgumentException(sprintf('sanitizePhoneNumberValue can only sanitize phone numbers, %s given', $property->getName()));
			}
			return;
		}
		if ($property->getValue() === '') {
			return;
		}
		try {
			$property->setValue($this->parsePhoneNumber($property->getValue()));
		} catch (InvalidArgumentException $e) {
			if ($throwOnData) {
				throw $e;
			}
			$property->setValue('');
		}
	}

	protected function sanitizeWebsite(IAccountProperty $property, bool $throwOnData = false) {
		if ($property->getName() !== self::PROPERTY_WEBSITE) {
			if ($throwOnData) {
				throw new InvalidArgumentException(sprintf('sanitizeWebsite can only sanitize web domains, %s given', $property->getName()));
			}
		}
		try {
			$property->setValue($this->parseWebsite($property->getValue()));
		} catch (InvalidArgumentException $e) {
			if ($throwOnData) {
				throw $e;
			}
			$property->setValue('');
		}
	}

	protected function updateUser(IUser $user, array $data, bool $throwOnData = false): array {
		$oldUserData = $this->getUser($user, false);
		$updated = true;

		if ($oldUserData !== $data) {
			$this->updateExistingUser($user, $data);
		} else {
			// nothing needs to be done if new and old data set are the same
			$updated = false;
		}

		if ($updated) {
			$this->eventDispatcher->dispatch(
				'OC\AccountManager::userUpdated',
				new GenericEvent($user, $data)
			);
		}

		return $data;
	}

	/**
	 * delete user from accounts table
	 *
	 * @param IUser $user
	 */
	public function deleteUser(IUser $user) {
		$uid = $user->getUID();
		$query = $this->connection->getQueryBuilder();
		$query->delete($this->table)
			->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
			->execute();

		$this->deleteUserData($user);
	}

	/**
	 * delete user from accounts table
	 *
	 * @param IUser $user
	 */
	public function deleteUserData(IUser $user): void {
		$uid = $user->getUID();
		$query = $this->connection->getQueryBuilder();
		$query->delete($this->dataTable)
			->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
			->execute();
	}

	/**
	 * get stored data from a given user
	 */
	protected function getUser(IUser $user, bool $insertIfNotExists = true): array {
		$uid = $user->getUID();
		$query = $this->connection->getQueryBuilder();
		$query->select('data')
			->from($this->table)
			->where($query->expr()->eq('uid', $query->createParameter('uid')))
			->setParameter('uid', $uid);
		$result = $query->executeQuery();
		$accountData = $result->fetchAll();
		$result->closeCursor();

		if (empty($accountData)) {
			$userData = $this->buildDefaultUserRecord($user);
			if ($insertIfNotExists) {
				$this->insertNewUser($user, $userData);
			}
			return $userData;
		}

		$userDataArray = $this->importFromJson($accountData[0]['data'], $uid);
		if ($userDataArray === null || $userDataArray === []) {
			return $this->buildDefaultUserRecord($user);
		}

		return $this->addMissingDefaultValues($userDataArray);
	}

	public function searchUsers(string $property, array $values): array {
		$chunks = array_chunk($values, 500);
		$query = $this->connection->getQueryBuilder();
		$query->select('*')
			->from($this->dataTable)
			->where($query->expr()->eq('name', $query->createNamedParameter($property)))
			->andWhere($query->expr()->in('value', $query->createParameter('values')));

		$matches = [];
		foreach ($chunks as $chunk) {
			$query->setParameter('values', $chunk, IQueryBuilder::PARAM_STR_ARRAY);
			$result = $query->executeQuery();

			while ($row = $result->fetch()) {
				$matches[$row['uid']] = $row['value'];
			}
			$result->closeCursor();
		}

		$result = array_merge($matches, $this->searchUsersForRelatedCollection($property, $values));

		return array_flip($result);
	}

	protected function searchUsersForRelatedCollection(string $property, array $values): array {
		switch ($property) {
			case IAccountManager::PROPERTY_EMAIL:
				return array_flip($this->searchUsers(IAccountManager::COLLECTION_EMAIL, $values));
			default:
				return [];
		}
	}

	/**
	 * check if we need to ask the server for email verification, if yes we create a cronjob
	 */
	protected function checkEmailVerification(IAccount $updatedAccount, array $oldData): void {
		try {
			$property = $updatedAccount->getProperty(self::PROPERTY_EMAIL);
		} catch (PropertyDoesNotExistException $e) {
			return;
		}
		$oldMail = isset($oldData[self::PROPERTY_EMAIL]) ? $oldData[self::PROPERTY_EMAIL]['value']['value'] : '';
		if ($oldMail !== $property->getValue()) {
			$this->jobList->add(VerifyUserData::class,
				[
					'verificationCode' => '',
					'data' => $property->getValue(),
					'type' => self::PROPERTY_EMAIL,
					'uid' => $updatedAccount->getUser()->getUID(),
					'try' => 0,
					'lastRun' => time()
				]
			);

			$property->setVerified(self::VERIFICATION_IN_PROGRESS);
		}
	}

	protected function checkLocalEmailVerification(IAccount $updatedAccount, array $oldData): void {
		$mailCollection = $updatedAccount->getPropertyCollection(self::COLLECTION_EMAIL);
		foreach ($mailCollection->getProperties() as $property) {
			if ($property->getLocallyVerified() !== self::NOT_VERIFIED) {
				continue;
			}
			if ($this->sendEmailVerificationEmail($updatedAccount->getUser(), $property->getValue())) {
				$property->setLocallyVerified(self::VERIFICATION_IN_PROGRESS);
			}
		}
	}

	protected function sendEmailVerificationEmail(IUser $user, string $email): bool {
		$ref = \substr(hash('sha256', $email), 0, 8);
		$key = $this->crypto->encrypt($email);
		$token = $this->verificationToken->create($user, 'verifyMail' . $ref, $email);

		$link = $this->urlGenerator->linkToRouteAbsolute('provisioning_api.Verification.verifyMail',
			[
				'userId' => $user->getUID(),
				'token' => $token,
				'key' => $key
			]);

		$emailTemplate = $this->mailer->createEMailTemplate('core.EmailVerification', [
			'link' => $link,
		]);

		if (!$this->l10n) {
			$this->l10n = $this->l10nfactory->get('core');
		}

		$emailTemplate->setSubject($this->l10n->t('%s email verification', [$this->defaults->getName()]));
		$emailTemplate->addHeader();
		$emailTemplate->addHeading($this->l10n->t('Email verification'));

		$emailTemplate->addBodyText(
			htmlspecialchars($this->l10n->t('Click the following button to confirm your email.')),
			$this->l10n->t('Click the following link to confirm your email.')
		);

		$emailTemplate->addBodyButton(
			htmlspecialchars($this->l10n->t('Confirm your email')),
			$link,
			false
		);
		$emailTemplate->addFooter();

		try {
			$message = $this->mailer->createMessage();
			$message->setTo([$email => $user->getDisplayName()]);
			$message->setFrom([Util::getDefaultEmailAddress('verification-noreply') => $this->defaults->getName()]);
			$message->useTemplate($emailTemplate);
			$this->mailer->send($message);
		} catch (Exception $e) {
			// Log the exception and continue
			$this->logger->info('Failed to send verification mail', [
				'app' => 'core',
				'exception' => $e
			]);
			return false;
		}
		return true;
	}

	/**
	 * make sure that all expected data are set
	 *
	 */
	protected function addMissingDefaultValues(array $userData): array {
		foreach ($userData as $i => $value) {
			if (!isset($value['verified'])) {
				$userData[$i]['verified'] = self::NOT_VERIFIED;
			}
		}

		return $userData;
	}

	protected function updateVerificationStatus(IAccount $updatedAccount, array $oldData): void {
		static $propertiesVerifiableByLookupServer = [
			self::PROPERTY_TWITTER,
			self::PROPERTY_WEBSITE,
			self::PROPERTY_EMAIL,
		];

		foreach ($propertiesVerifiableByLookupServer as $propertyName) {
			try {
				$property = $updatedAccount->getProperty($propertyName);
			} catch (PropertyDoesNotExistException $e) {
				continue;
			}
			$wasVerified = isset($oldData[$propertyName])
				&& isset($oldData[$propertyName]['verified'])
				&& $oldData[$propertyName]['verified'] === self::VERIFIED;
			if ((!isset($oldData[$propertyName])
					|| !isset($oldData[$propertyName]['value'])
					|| $property->getValue() !== $oldData[$propertyName]['value'])
				&& ($property->getVerified() !== self::NOT_VERIFIED
					|| $wasVerified)
				) {
				$property->setVerified(self::NOT_VERIFIED);
			}
		}
	}

	/**
	 * add new user to accounts table
	 *
	 * @param IUser $user
	 * @param array $data
	 */
	protected function insertNewUser(IUser $user, array $data): void {
		$uid = $user->getUID();
		$jsonEncodedData = $this->prepareJson($data);
		$query = $this->connection->getQueryBuilder();
		$query->insert($this->table)
			->values(
				[
					'uid' => $query->createNamedParameter($uid),
					'data' => $query->createNamedParameter($jsonEncodedData),
				]
			)
			->executeStatement();

		$this->deleteUserData($user);
		$this->writeUserData($user, $data);
	}

	protected function prepareJson(array $data): string {
		$preparedData = [];
		foreach ($data as $dataRow) {
			$propertyName = $dataRow['name'];
			unset($dataRow['name']);

			if (isset($dataRow['locallyVerified']) && $dataRow['locallyVerified'] === self::NOT_VERIFIED) {
				// do not write default value, save DB space
				unset($dataRow['locallyVerified']);
			}

			if (!$this->isCollection($propertyName)) {
				$preparedData[$propertyName] = $dataRow;
				continue;
			}
			if (!isset($preparedData[$propertyName])) {
				$preparedData[$propertyName] = [];
			}
			$preparedData[$propertyName][] = $dataRow;
		}
		return json_encode($preparedData);
	}

	protected function importFromJson(string $json, string $userId): ?array {
		$result = [];
		$jsonArray = json_decode($json, true);
		$jsonError = json_last_error();
		if ($jsonError !== JSON_ERROR_NONE) {
			$this->logger->critical(
				'User data of {uid} contained invalid JSON (error {json_error}), hence falling back to a default user record',
				[
					'uid' => $userId,
					'json_error' => $jsonError
				]
			);
			return null;
		}
		foreach ($jsonArray as $propertyName => $row) {
			if (!$this->isCollection($propertyName)) {
				$result[] = array_merge($row, ['name' => $propertyName]);
				continue;
			}
			foreach ($row as $singleRow) {
				$result[] = array_merge($singleRow, ['name' => $propertyName]);
			}
		}
		return $result;
	}

	/**
	 * update existing user in accounts table
	 *
	 * @param IUser $user
	 * @param array $data
	 */
	protected function updateExistingUser(IUser $user, array $data): void {
		$uid = $user->getUID();
		$jsonEncodedData = $this->prepareJson($data);
		$query = $this->connection->getQueryBuilder();
		$query->update($this->table)
			->set('data', $query->createNamedParameter($jsonEncodedData))
			->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
			->executeStatement();

		$this->deleteUserData($user);
		$this->writeUserData($user, $data);
	}

	protected function writeUserData(IUser $user, array $data): void {
		$query = $this->connection->getQueryBuilder();
		$query->insert($this->dataTable)
			->values(
				[
					'uid' => $query->createNamedParameter($user->getUID()),
					'name' => $query->createParameter('name'),
					'value' => $query->createParameter('value'),
				]
			);
		$this->writeUserDataProperties($query, $data);
	}

	protected function writeUserDataProperties(IQueryBuilder $query, array $data): void {
		foreach ($data as $property) {
			if ($property['name'] === self::PROPERTY_AVATAR) {
				continue;
			}

			$query->setParameter('name', $property['name'])
				->setParameter('value', $property['value'] ?? '');
			$query->executeStatement();
		}
	}

	/**
	 * build default user record in case not data set exists yet
	 *
	 * @param IUser $user
	 * @return array
	 */
	protected function buildDefaultUserRecord(IUser $user) {
		return [

			[
				'name' => self::PROPERTY_DISPLAYNAME,
				'value' => $user->getDisplayName(),
				'scope' => self::SCOPE_FEDERATED,
				'verified' => self::NOT_VERIFIED,
			],

			[
				'name' => self::PROPERTY_ADDRESS,
				'value' => '',
				'scope' => self::SCOPE_LOCAL,
				'verified' => self::NOT_VERIFIED,
			],

			[
				'name' => self::PROPERTY_WEBSITE,
				'value' => '',
				'scope' => self::SCOPE_LOCAL,
				'verified' => self::NOT_VERIFIED,
			],

			[
				'name' => self::PROPERTY_EMAIL,
				'value' => $user->getEMailAddress(),
				'scope' => self::SCOPE_FEDERATED,
				'verified' => self::NOT_VERIFIED,
			],

			[
				'name' => self::PROPERTY_AVATAR,
				'scope' => self::SCOPE_FEDERATED
			],

			[
				'name' => self::PROPERTY_PHONE,
				'value' => '',
				'scope' => self::SCOPE_LOCAL,
				'verified' => self::NOT_VERIFIED,
			],

			[
				'name' => self::PROPERTY_TWITTER,
				'value' => '',
				'scope' => self::SCOPE_LOCAL,
				'verified' => self::NOT_VERIFIED,
			],

		];
	}

	private function arrayDataToCollection(IAccount $account, array $data): IAccountPropertyCollection {
		$collection = $account->getPropertyCollection($data['name']);

		$p = new AccountProperty(
			$data['name'],
			$data['value'] ?? '',
			$data['scope'] ?? self::SCOPE_LOCAL,
			$data['verified'] ?? self::NOT_VERIFIED,
			''
		);
		$p->setLocallyVerified($data['locallyVerified'] ?? self::NOT_VERIFIED);
		$collection->addProperty($p);

		return $collection;
	}

	private function parseAccountData(IUser $user, $data): Account {
		$account = new Account($user);
		foreach ($data as $accountData) {
			if ($this->isCollection($accountData['name'])) {
				$account->setPropertyCollection($this->arrayDataToCollection($account, $accountData));
			} else {
				$account->setProperty($accountData['name'], $accountData['value'] ?? '', $accountData['scope'] ?? self::SCOPE_LOCAL, $accountData['verified'] ?? self::NOT_VERIFIED);
				if (isset($accountData['locallyVerified'])) {
					$property = $account->getProperty($accountData['name']);
					$property->setLocallyVerified($accountData['locallyVerified']);
				}
			}
		}
		return $account;
	}

	public function getAccount(IUser $user): IAccount {
		return $this->parseAccountData($user, $this->getUser($user));
	}

	public function updateAccount(IAccount $account): void {
		$this->testValueLengths(iterator_to_array($account->getAllProperties()), true);
		try {
			$property = $account->getProperty(self::PROPERTY_PHONE);
			$this->sanitizePhoneNumberValue($property);
		} catch (PropertyDoesNotExistException $e) {
			//  valid case, nothing to do
		}

		try {
			$property = $account->getProperty(self::PROPERTY_WEBSITE);
			$this->sanitizeWebsite($property);
		} catch (PropertyDoesNotExistException $e) {
			//  valid case, nothing to do
		}

		static $allowedScopes = [
			self::SCOPE_PRIVATE,
			self::SCOPE_LOCAL,
			self::SCOPE_FEDERATED,
			self::SCOPE_PUBLISHED,
			self::VISIBILITY_PRIVATE,
			self::VISIBILITY_CONTACTS_ONLY,
			self::VISIBILITY_PUBLIC,
		];
		foreach ($account->getAllProperties() as $property) {
			$this->testPropertyScope($property, $allowedScopes, true);
		}

		$oldData = $this->getUser($account->getUser(), false);
		$this->updateVerificationStatus($account, $oldData);
		$this->checkEmailVerification($account, $oldData);
		$this->checkLocalEmailVerification($account, $oldData);

		$data = [];
		foreach ($account->getAllProperties() as $property) {
			/** @var IAccountProperty $property */
			$data[] = [
				'name' => $property->getName(),
				'value' => $property->getValue(),
				'scope' => $property->getScope(),
				'verified' => $property->getVerified(),
				'locallyVerified' => $property->getLocallyVerified(),
			];
		}

		$this->updateUser($account->getUser(), $data, true);
	}
}