3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use DivineOmega\DOFileCachePSR6\CacheItemPool;
25 use DivineOmega\PasswordExposed;
28 use Friendica\Content\Pager;
29 use Friendica\Core\Hook;
30 use Friendica\Core\L10n;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Search;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
39 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
40 use Friendica\Network\HTTPException;
41 use Friendica\Object\Image;
42 use Friendica\Protocol\Delivery;
43 use Friendica\Security\TwoFactor\Model\AppSpecificPassword;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Images;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
54 * This class handles User related functions
61 * PAGE_FLAGS_NORMAL is a typical personal profile account
62 * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
63 * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
64 * write access to wall and comments (no email and not included in page owner's ACL lists)
65 * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
69 const PAGE_FLAGS_NORMAL = 0;
70 const PAGE_FLAGS_SOAPBOX = 1;
71 const PAGE_FLAGS_COMMUNITY = 2;
72 const PAGE_FLAGS_FREELOVE = 3;
73 const PAGE_FLAGS_BLOG = 4;
74 const PAGE_FLAGS_PRVGROUP = 5;
82 * ACCOUNT_TYPE_PERSON - the account belongs to a person
83 * Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
85 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
86 * Associated page type: PAGE_FLAGS_SOAPBOX
88 * ACCOUNT_TYPE_NEWS - the account is a news reflector
89 * Associated page type: PAGE_FLAGS_SOAPBOX
91 * ACCOUNT_TYPE_COMMUNITY - the account is community group
92 * Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
94 * ACCOUNT_TYPE_RELAY - the account is a relay
95 * This will only be assigned to contacts, not to user accounts
98 const ACCOUNT_TYPE_PERSON = 0;
99 const ACCOUNT_TYPE_ORGANISATION = 1;
100 const ACCOUNT_TYPE_NEWS = 2;
101 const ACCOUNT_TYPE_COMMUNITY = 3;
102 const ACCOUNT_TYPE_RELAY = 4;
103 const ACCOUNT_TYPE_DELETED = 127;
108 private static $owner;
111 * Returns the numeric account type by their string
113 * @param string $accounttype as string constant
114 * @return int|null Numeric account type - or null when not set
116 public static function getAccountTypeByString(string $accounttype)
118 switch ($accounttype) {
120 return User::ACCOUNT_TYPE_PERSON;
123 return User::ACCOUNT_TYPE_ORGANISATION;
126 return User::ACCOUNT_TYPE_NEWS;
129 return User::ACCOUNT_TYPE_COMMUNITY;
135 * Get the Uri-Id of the system account
139 public static function getSystemUriId(): int
141 $system = self::getSystemAccount();
142 return $system['uri-id'] ?? 0;
146 * Fetch the system account
148 * @return array system account
150 public static function getSystemAccount(): array
152 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
153 if (!DBA::isResult($system)) {
154 self::createSystemAccount();
155 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
156 if (!DBA::isResult($system)) {
161 $system['sprvkey'] = $system['uprvkey'] = $system['prvkey'];
162 $system['spubkey'] = $system['upubkey'] = $system['pubkey'];
163 $system['nickname'] = $system['nick'];
164 $system['page-flags'] = User::PAGE_FLAGS_SOAPBOX;
165 $system['account-type'] = $system['contact-type'];
166 $system['guid'] = '';
167 $system['picdate'] = '';
168 $system['theme'] = '';
169 $system['publish'] = false;
170 $system['net-publish'] = false;
171 $system['hide-friends'] = true;
172 $system['hidewall'] = true;
173 $system['prv_keywords'] = '';
174 $system['pub_keywords'] = '';
175 $system['address'] = '';
176 $system['locality'] = '';
177 $system['region'] = '';
178 $system['postal-code'] = '';
179 $system['country-name'] = '';
180 $system['homepage'] = (string)DI::baseUrl();
181 $system['dob'] = '0000-00-00';
183 // Ensure that the user contains data
184 $user = DBA::selectFirst('user', ['prvkey', 'guid', 'language'], ['uid' => 0]);
185 if (empty($user['prvkey']) || empty($user['guid'])) {
187 'username' => $system['name'],
188 'nickname' => $system['nick'],
189 'register_date' => $system['created'],
190 'pubkey' => $system['pubkey'],
191 'prvkey' => $system['prvkey'],
192 'spubkey' => $system['spubkey'],
193 'sprvkey' => $system['sprvkey'],
194 'guid' => System::createUUID(),
196 'page-flags' => User::PAGE_FLAGS_SOAPBOX,
197 'account-type' => User::ACCOUNT_TYPE_RELAY,
200 DBA::update('user', $fields, ['uid' => 0]);
202 $system['guid'] = $fields['guid'];
204 $system['guid'] = $user['guid'];
205 $system['language'] = $user['language'];
212 * Create the system account
216 private static function createSystemAccount()
218 $system_actor_name = self::getActorName();
219 if (empty($system_actor_name)) {
223 $keys = Crypto::newKeypair(4096);
224 if ($keys === false) {
225 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
230 'created' => DateTimeFormat::utcNow(),
232 'network' => Protocol::ACTIVITYPUB,
233 'name' => 'System Account',
234 'addr' => $system_actor_name . '@' . DI::baseUrl()->getHost(),
235 'nick' => $system_actor_name,
236 'url' => DI::baseUrl() . '/friendica',
237 'pubkey' => $keys['pubkey'],
238 'prvkey' => $keys['prvkey'],
241 'contact-type' => Contact::TYPE_RELAY, // In AP this is translated to 'Application'
242 'name-date' => DateTimeFormat::utcNow(),
243 'uri-date' => DateTimeFormat::utcNow(),
244 'avatar-date' => DateTimeFormat::utcNow(),
246 'baseurl' => DI::baseUrl(),
249 $system['avatar'] = $system['photo'] = Contact::getDefaultAvatar($system, Proxy::SIZE_SMALL);
250 $system['thumb'] = Contact::getDefaultAvatar($system, Proxy::SIZE_THUMB);
251 $system['micro'] = Contact::getDefaultAvatar($system, Proxy::SIZE_MICRO);
252 $system['nurl'] = Strings::normaliseLink($system['url']);
253 $system['gsid'] = GServer::getID($system['baseurl']);
255 Contact::insert($system);
259 * Detect a usable actor name
261 * @return string actor account name
263 public static function getActorName(): string
265 $system_actor_name = DI::config()->get('system', 'actor_name');
266 if (!empty($system_actor_name)) {
267 $self = Contact::selectFirst(['nick'], ['uid' => 0, 'self' => true]);
268 if (!empty($self['nick'])) {
269 if ($self['nick'] != $system_actor_name) {
270 // Reset the actor name to the already used name
271 DI::config()->set('system', 'actor_name', $self['nick']);
272 $system_actor_name = $self['nick'];
275 return $system_actor_name;
278 // List of possible actor names
279 $possible_accounts = ['friendica', 'actor', 'system', 'internal'];
280 foreach ($possible_accounts as $name) {
281 if (!DBA::exists('user', ['nickname' => $name]) && !DBA::exists('userd', ['username' => $name])) {
282 DI::config()->set('system', 'actor_name', $name);
290 * Returns true if a user record exists with the provided id
297 public static function exists(int $uid): bool
299 return DBA::exists('user', ['uid' => $uid]);
303 * @param integer $uid
304 * @param array $fields
305 * @return array|boolean User record if it exists, false otherwise
308 public static function getById(int $uid, array $fields = [])
310 return !empty($uid) ? DBA::selectFirst('user', $fields, ['uid' => $uid]) : [];
314 * Returns a user record based on it's GUID
316 * @param string $guid The guid of the user
317 * @param array $fields The fields to retrieve
318 * @param bool $active True, if only active records are searched
320 * @return array|boolean User record if it exists, false otherwise
323 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
326 $cond = ['guid' => $guid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
328 $cond = ['guid' => $guid];
331 return DBA::selectFirst('user', $fields, $cond);
335 * @param string $nickname
336 * @param array $fields
337 * @return array|boolean User record if it exists, false otherwise
340 public static function getByNickname(string $nickname, array $fields = [])
342 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
346 * Set static settings for community user accounts
348 * @param integer $uid
351 public static function setCommunityUserSettings(int $uid)
353 $user = self::getById($uid, ['account-type', 'page-flags']);
354 if ($user['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
358 DI::pConfig()->set($uid, 'system', 'unlisted', true);
362 'allow_gid' => $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP ? '<' . Circle::FOLLOWERS . '>' : '',
369 User::update($fields, $uid);
371 Profile::update(['hide-friends' => true], $uid);
375 * Returns the user id of a given profile URL
379 * @return integer user id
382 public static function getIdForURL(string $url): int
384 // Avoid database queries when the local node hostname isn't even part of the url.
385 if (!Contact::isLocal($url)) {
389 $self = Contact::selectFirst(['uid'], ['self' => true, 'nurl' => Strings::normaliseLink($url)]);
390 if (!empty($self['uid'])) {
394 $self = Contact::selectFirst(['uid'], ['self' => true, 'addr' => $url]);
395 if (!empty($self['uid'])) {
399 $self = Contact::selectFirst(['uid'], ['self' => true, 'alias' => [$url, Strings::normaliseLink($url)]]);
400 if (!empty($self['uid'])) {
408 * Get a user based on its email
410 * @param string $email
411 * @param array $fields
412 * @return array|boolean User record if it exists, false otherwise
415 public static function getByEmail(string $email, array $fields = [])
417 return DBA::selectFirst('user', $fields, ['email' => $email]);
421 * Fetch the user array of the administrator. The first one if there are several.
423 * @param array $fields
427 public static function getFirstAdmin(array $fields = []): array
429 if (!empty(DI::config()->get('config', 'admin_nickname'))) {
430 return self::getByNickname(DI::config()->get('config', 'admin_nickname'), $fields);
433 return self::getAdminList()[0] ?? [];
437 * Get owner data by user id
440 * @param boolean $repairMissing Repair the owner data if it's missing
441 * @return boolean|array
444 public static function getOwnerDataById(int $uid, bool $repairMissing = true)
447 return self::getSystemAccount();
450 if (!empty(self::$owner[$uid])) {
451 return self::$owner[$uid];
454 $owner = DBA::selectFirst('owner-view', [], ['uid' => $uid]);
455 if (!DBA::isResult($owner)) {
456 if (!self::exists($uid) || !$repairMissing) {
459 if (!DBA::exists('profile', ['uid' => $uid])) {
460 DBA::insert('profile', ['uid' => $uid]);
462 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
463 Contact::createSelfFromUserId($uid);
465 $owner = self::getOwnerDataById($uid, false);
468 if (empty($owner['nickname'])) {
472 if (!$repairMissing || $owner['account_expired']) {
476 // Check if the returned data is valid, otherwise fix it. See issue #6122
478 // Check for correct url and normalised nurl
479 $url = DI::baseUrl() . '/profile/' . $owner['nickname'];
480 $repair = empty($owner['network']) || ($owner['url'] != $url) || ($owner['nurl'] != Strings::normaliseLink($owner['url']));
483 // Check if "addr" is present and correct
484 $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
485 $repair = ($addr != $owner['addr']) || empty($owner['prvkey']) || empty($owner['pubkey']);
489 // Check if the avatar field is filled and the photo directs to the correct path
490 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
491 if (DBA::isResult($avatar)) {
492 $repair = empty($owner['avatar']) || !strpos($owner['photo'], $avatar['resource-id']);
497 Contact::updateSelfFromUserID($uid);
498 // Return the corrected data and avoid a loop
499 $owner = self::getOwnerDataById($uid, false);
502 self::$owner[$uid] = $owner;
507 * Get owner data by nick name
510 * @return boolean|array
513 public static function getOwnerDataByNick(string $nick)
515 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
517 if (!DBA::isResult($user)) {
521 return self::getOwnerDataById($user['uid']);
525 * Returns the default circle for a given user
527 * @param int $uid User id
529 * @return int circle id
532 public static function getDefaultCircle(int $uid): int
534 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
535 if (DBA::isResult($user)) {
536 $default_circle = $user['def_gid'];
541 return $default_circle;
545 * Returns the default circle for groups for a given user
547 * @param int $uid User id
549 * @return int circle id
552 public static function getDefaultGroupCircle(int $uid): int
554 $default_circle = DI::pConfig()->get($uid, 'system', 'default-group-gid');
555 if (empty($default_circle)) {
556 $default_circle = self::getDefaultCircle($uid);
559 return $default_circle;
563 * Fetch the language code from the given user. If the code is invalid, return the system language
565 * @param integer $uid User-Id
568 public static function getLanguageCode(int $uid): string
570 $owner = self::getOwnerDataById($uid);
571 $language = DI::l10n()->toISO6391($owner['language']);
572 if (in_array($language, array_keys(DI::l10n()->getLanguageCodes()))) {
575 return DI::l10n()->toISO6391(DI::config()->get('system', 'language'));
579 * Fetch the wanted languages for a given user
581 * @param integer $uid
584 public static function getWantedLanguages(int $uid): array
586 return DI::pConfig()->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]) ?? [];
590 * Get a list of all languages that are used by the users
594 public static function getLanguages(): array
596 $cachekey = 'user:getLanguages';
597 $languages = DI::cache()->get($cachekey);
598 if (!is_null($languages)) {
602 $supported = array_keys(DI::l10n()->getLanguageCodes());
606 $condition = ["`verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired` AND `uid` > ?", 0];
608 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
609 if (!empty($abandon_days)) {
610 $condition = DBA::mergeConditions($condition, ["`last-activity` > ?", DateTimeFormat::utc('now - ' . $abandon_days . ' days')]);
613 $users = DBA::select('user', ['uid', 'language'], $condition);
614 while ($user = DBA::fetch($users)) {
615 $uids[] = $user['uid'];
616 $code = DI::l10n()->toISO6391($user['language']);
617 if (!in_array($code, $supported)) {
620 $languages[$code] = $code;
624 $channels = DBA::select('pconfig', ['uid', 'v'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'channel', 'languages', '']);
625 while ($channel = DBA::fetch($channels)) {
626 if (!in_array($channel['uid'], $uids)) {
629 $values = unserialize($channel['v']);
630 if (!empty($values) && is_array($values)) {
631 foreach ($values as $language) {
632 $language = DI::l10n()->toISO6391($language);
633 $languages[$language] = $language;
637 DBA::close($channels);
640 $languages = array_keys($languages);
641 DI::cache()->set($cachekey, $languages);
647 * Authenticate a user with a clear text password
649 * Returns the user id associated with a successful password authentication
651 * @param mixed $user_info
652 * @param string $password
653 * @param bool $third_party
654 * @return int User Id if authentication is successful
655 * @throws HTTPException\ForbiddenException
656 * @throws HTTPException\NotFoundException
658 public static function getIdFromPasswordAuthentication($user_info, string $password, bool $third_party = false): int
660 // Addons registered with the "authenticate" hook may create the user on the
661 // fly. `getAuthenticationInfo` will fail if the user doesn't exist yet. If
662 // the user doesn't exist, we should give the addons a chance to create the
663 // user in our database, if applicable, before re-throwing the exception if
666 $user = self::getAuthenticationInfo($user_info);
667 } catch (Exception $e) {
668 $username = (is_string($user_info) ? $user_info : $user_info['nickname'] ?? '');
670 // Addons can create users, and since this 'catch' branch should only
671 // execute if getAuthenticationInfo can't find an existing user, that's
672 // exactly what will happen here. Creating a numeric username would create
673 // ambiguity with user IDs, possibly opening up an attack vector.
674 // So let's be very careful about that.
675 if (empty($username) || is_numeric($username)) {
679 return self::getIdFromAuthenticateHooks($username, $password);
682 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
683 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
684 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
687 } elseif (strpos($user['password'], '$') === false) {
688 //Legacy hash that has not been replaced by a new hash yet
689 if (self::hashPasswordLegacy($password) === $user['password']) {
690 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
694 } elseif (!empty($user['legacy_password'])) {
695 //Legacy hash that has been double-hashed and not replaced by a new hash yet
696 //Warning: `legacy_password` is not necessary in sync with the content of `password`
697 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
698 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
702 } elseif (password_verify($password, $user['password'])) {
704 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
705 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
710 return self::getIdFromAuthenticateHooks($user['nickname'], $password); // throws
713 throw new HTTPException\ForbiddenException(DI::l10n()->t('Login failed'));
717 * Try to obtain a user ID via "authenticate" hook addons
719 * Returns the user id associated with a successful password authentication
721 * @param string $username
722 * @param string $password
723 * @return int User Id if authentication is successful
724 * @throws HTTPException\ForbiddenException
726 public static function getIdFromAuthenticateHooks(string $username, string $password): int
729 'username' => $username,
730 'password' => $password,
731 'authenticated' => 0,
732 'user_record' => null
736 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
737 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
738 * and later addons should not interfere with an earlier one that succeeded.
740 Hook::callAll('authenticate', $addon_auth);
742 if ($addon_auth['authenticated'] && $addon_auth['user_record']) {
743 return $addon_auth['user_record']['uid'];
746 throw new HTTPException\ForbiddenException(DI::l10n()->t('Login failed'));
750 * Returns authentication info from various parameters types
752 * User info can be any of the following:
755 * - User email or username or nickname
756 * - User array with at least the uid and the hashed password
758 * @param mixed $user_info
759 * @return array|null Null if not found/determined
760 * @throws HTTPException\NotFoundException
762 public static function getAuthenticationInfo($user_info)
766 if (is_object($user_info) || is_array($user_info)) {
767 if (is_object($user_info)) {
768 $user = (array) $user_info;
775 || !isset($user['password'])
776 || !isset($user['legacy_password'])
778 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
780 } elseif (is_int($user_info) || is_string($user_info)) {
781 if (is_int($user_info)) {
782 $user = DBA::selectFirst(
784 ['uid', 'nickname', 'password', 'legacy_password'],
788 'account_expired' => 0,
789 'account_removed' => 0,
794 $fields = ['uid', 'nickname', 'password', 'legacy_password'];
796 "(`email` = ? OR `username` = ? OR `nickname` = ?)
797 AND `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`",
798 $user_info, $user_info, $user_info
800 $user = DBA::selectFirst('user', $fields, $condition);
803 if (!DBA::isResult($user)) {
804 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found'));
812 * Update the day of the last activity of the given user
814 * @param integer $uid
817 public static function updateLastActivity(int $uid)
823 $user = User::getById($uid, ['last-activity']);
828 $current_day = DateTimeFormat::utcNow('Y-m-d');
830 if ($user['last-activity'] != $current_day) {
831 User::update(['last-activity' => $current_day], $uid);
832 // Set the last activity for all identities of the user
833 DBA::update('user', ['last-activity' => $current_day], ['parent-uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
838 * Generates a human-readable random password
843 public static function generateNewPassword(): string
845 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
849 * Checks if the provided plaintext password has been exposed or not
851 * @param string $password
855 public static function isPasswordExposed(string $password): bool
857 $cache = new CacheItemPool();
858 $cache->changeConfig([
859 'cacheDirectory' => System::getTempPath() . '/password-exposed-cache/',
863 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
865 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
866 } catch (Exception $e) {
867 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
868 'code' => $e->getCode(),
869 'file' => $e->getFile(),
870 'line' => $e->getLine(),
871 'trace' => $e->getTraceAsString()
879 * Legacy hashing function, kept for password migration purposes
881 * @param string $password
884 private static function hashPasswordLegacy(string $password): string
886 return hash('whirlpool', $password);
890 * Global user password hashing function
892 * @param string $password
896 public static function hashPassword(string $password): string
898 if (!trim($password)) {
899 throw new Exception(DI::l10n()->t('Password can\'t be empty'));
902 return password_hash($password, PASSWORD_DEFAULT);
906 * Allowed characters are a-z, A-Z, 0-9 and special characters except white spaces and accentuated letters.
908 * Password length is limited to 72 characters if the current default password hashing algorithm is Blowfish.
909 * From the manual: "Using the PASSWORD_BCRYPT as the algorithm, will result in the password parameter being
910 * truncated to a maximum length of 72 bytes."
912 * @see https://www.php.net/manual/en/function.password-hash.php#refsect1-function.password-hash-parameters
914 * @param string|null $delimiter Whether the regular expression is meant to be wrapper in delimiter characters
917 public static function getPasswordRegExp(string $delimiter = null): string
919 $allowed_characters = ':!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
922 $allowed_characters = preg_quote($allowed_characters, $delimiter);
925 return '^[a-zA-Z0-9' . $allowed_characters . ']' . (PASSWORD_DEFAULT === PASSWORD_BCRYPT ? '{1,72}' : '+') . '$';
929 * Updates a user row with a new plaintext password
932 * @param string $password
936 public static function updatePassword(int $uid, string $password): bool
938 $password = trim($password);
940 if (empty($password)) {
941 throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
944 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
945 throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
948 if (PASSWORD_DEFAULT === PASSWORD_BCRYPT && strlen($password) > 72) {
949 throw new Exception(DI::l10n()->t('The password length is limited to 72 characters.'));
952 if (!preg_match('/' . self::getPasswordRegExp('/') . '/', $password)) {
953 throw new Exception(DI::l10n()->t("The password can't contain white spaces nor accentuated letters"));
956 return self::updatePasswordHashed($uid, self::hashPassword($password));
960 * Updates a user row with a new hashed password.
961 * Empties the password reset token field just in case.
964 * @param string $password_hashed
968 private static function updatePasswordHashed(int $uid, string $password_hashed): bool
971 'password' => $password_hashed,
973 'pwdreset_time' => null,
974 'legacy_password' => false
976 return DBA::update('user', $fields, ['uid' => $uid]);
980 * Returns if the given uid is valid and in the admin list
987 public static function isSiteAdmin(int $uid): bool
989 return DBA::exists('user', [
991 'email' => self::getAdminEmailList()
996 * Returns if the given uid is valid and a moderator
1003 public static function isModerator(int $uid): bool
1005 // @todo Replace with a moderator check in the future
1006 return self::isSiteAdmin($uid);
1010 * Checks if a nickname is in the list of the forbidden nicknames
1012 * Check if a nickname is forbidden from registration on the node by the
1013 * admin. Forbidden nicknames (e.g. role names) can be configured in the
1016 * @param string $nickname The nickname that should be checked
1017 * @return boolean True is the nickname is blocked on the node
1019 public static function isNicknameBlocked(string $nickname): bool
1021 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
1022 if (!empty($forbidden_nicknames)) {
1023 $forbidden = explode(',', $forbidden_nicknames);
1024 $forbidden = array_map('trim', $forbidden);
1029 // Add the name of the internal actor to the "forbidden" list
1030 $actor_name = self::getActorName();
1031 if (!empty($actor_name)) {
1032 $forbidden[] = $actor_name;
1035 if (empty($forbidden)) {
1039 // check if the nickname is in the list of blocked nicknames
1040 if (in_array(strtolower($nickname), $forbidden)) {
1044 // else return false
1049 * Get avatar link for given user
1051 * @param array $user
1052 * @param string $size One of the Proxy::SIZE_* constants
1053 * @return string avatar link
1056 public static function getAvatarUrl(array $user, string $size = ''): string
1058 if (empty($user['nickname'])) {
1059 DI::logger()->warning('Missing user nickname key');
1062 $url = DI::baseUrl() . '/photo/';
1065 case Proxy::SIZE_MICRO:
1069 case Proxy::SIZE_THUMB:
1082 $photo = Photo::selectFirst(['type', 'created', 'edited', 'updated'], ["scale" => $scale, 'uid' => $user['uid'], 'profile' => true]);
1083 if (!empty($photo)) {
1084 $updated = max($photo['created'], $photo['edited'], $photo['updated']);
1085 $mimetype = $photo['type'];
1088 return $url . $user['nickname'] . Images::getExtensionByMimeType($mimetype) . ($updated ? '?ts=' . strtotime($updated) : '');
1092 * Get banner link for given user
1094 * @param array $user
1095 * @return string banner link
1098 public static function getBannerUrl(array $user): string
1100 if (empty($user['nickname'])) {
1101 DI::logger()->warning('Missing user nickname key');
1104 $url = DI::baseUrl() . '/photo/banner/';
1109 $photo = Photo::selectFirst(['type', 'created', 'edited', 'updated'], ["scale" => 3, 'uid' => $user['uid'], 'photo-type' => Photo::USER_BANNER]);
1110 if (!empty($photo)) {
1111 $updated = max($photo['created'], $photo['edited'], $photo['updated']);
1112 $mimetype = $photo['type'];
1114 // Only for the RC phase: Don't return an image link for the default picture
1118 return $url . $user['nickname'] . Images::getExtensionByMimeType($mimetype) . ($updated ? '?ts=' . strtotime($updated) : '');
1122 * Catch-all user creation function
1124 * Creates a user from the provided data array, either form fields or OpenID.
1125 * Required: { username, nickname, email } or { openid_url }
1127 * Performs the following:
1128 * - Sends to the OpenId auth URL (if relevant)
1129 * - Creates new key pairs for crypto
1130 * - Create self-contact
1131 * - Create profile image
1133 * @param array $data
1135 * @throws ErrorException
1136 * @throws HTTPException\InternalServerErrorException
1137 * @throws ImagickException
1140 public static function create(array $data): array
1142 $return = ['user' => null, 'password' => ''];
1144 $using_invites = DI::config()->get('system', 'invitation_only');
1146 $invite_id = !empty($data['invite_id']) ? trim($data['invite_id']) : '';
1147 $username = !empty($data['username']) ? trim($data['username']) : '';
1148 $nickname = !empty($data['nickname']) ? trim($data['nickname']) : '';
1149 $email = !empty($data['email']) ? trim($data['email']) : '';
1150 $openid_url = !empty($data['openid_url']) ? trim($data['openid_url']) : '';
1151 $photo = !empty($data['photo']) ? trim($data['photo']) : '';
1152 $password = !empty($data['password']) ? trim($data['password']) : '';
1153 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
1154 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
1155 $blocked = !empty($data['blocked']);
1156 $verified = !empty($data['verified']);
1157 $language = !empty($data['language']) ? trim($data['language']) : 'en';
1159 $netpublish = $publish = !empty($data['profile_publish_reg']);
1161 if ($password1 != $confirm) {
1162 throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
1163 } elseif ($password1 != '') {
1164 $password = $password1;
1167 if ($using_invites) {
1169 throw new Exception(DI::l10n()->t('An invitation is required.'));
1172 if (!Register::existsByHash($invite_id)) {
1173 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
1177 /// @todo Check if this part is really needed. We should have fetched all this data in advance
1178 if (empty($username) || empty($email) || empty($nickname)) {
1180 if (!Network::isUrlValid($openid_url)) {
1181 throw new Exception(DI::l10n()->t('Invalid OpenID url'));
1183 $_SESSION['register'] = 1;
1184 $_SESSION['openid'] = $openid_url;
1186 $openid = new LightOpenID(DI::baseUrl()->getHost());
1187 $openid->identity = $openid_url;
1188 $openid->returnUrl = DI::baseUrl() . '/openid';
1189 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
1190 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
1192 $authurl = $openid->authUrl();
1193 } catch (Exception $e) {
1194 throw new Exception(DI::l10n()->t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '<br />' . DI::l10n()->t('The error message was:') . $e->getMessage(), 0, $e);
1196 System::externalRedirect($authurl);
1200 throw new Exception(DI::l10n()->t('Please enter the required information.'));
1203 if (!Network::isUrlValid($openid_url)) {
1207 // collapse multiple spaces in name
1208 $username = preg_replace('/ +/', ' ', $username);
1210 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
1211 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
1213 if ($username_min_length > $username_max_length) {
1214 Logger::error(DI::l10n()->t('system.username_min_length (%s) and system.username_max_length (%s) are excluding each other, swapping values.', $username_min_length, $username_max_length));
1215 $tmp = $username_min_length;
1216 $username_min_length = $username_max_length;
1217 $username_max_length = $tmp;
1220 if (mb_strlen($username) < $username_min_length) {
1221 throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
1224 if (mb_strlen($username) > $username_max_length) {
1225 throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
1228 // So now we are just looking for a space in the display name.
1229 $loose_reg = DI::config()->get('system', 'no_regfullname');
1231 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
1232 if (strpos($username, ' ') === false) {
1233 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
1237 if (!Network::isEmailDomainAllowed($email)) {
1238 throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
1241 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
1242 throw new Exception(DI::l10n()->t('Not a valid email address.'));
1244 if (self::isNicknameBlocked($nickname)) {
1245 throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
1248 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
1249 throw new Exception(DI::l10n()->t('Cannot use that email.'));
1252 // Disallow somebody creating an account using openid that uses the admin email address,
1253 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
1254 if (strlen($openid_url) && in_array(strtolower($email), self::getAdminEmailList())) {
1255 throw new Exception(DI::l10n()->t('Cannot use that email.'));
1258 $nickname = $data['nickname'] = strtolower($nickname);
1260 if (!preg_match('/^[a-z0-9][a-z0-9_]*$/', $nickname)) {
1261 throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
1264 // Check existing and deleted accounts for this nickname.
1266 DBA::exists('user', ['nickname' => $nickname])
1267 || DBA::exists('userd', ['username' => $nickname])
1269 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
1272 $new_password = strlen($password) ? $password : User::generateNewPassword();
1273 $new_password_encoded = self::hashPassword($new_password);
1275 $return['password'] = $new_password;
1277 $keys = Crypto::newKeypair(4096);
1278 if ($keys === false) {
1279 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
1282 $prvkey = $keys['prvkey'];
1283 $pubkey = $keys['pubkey'];
1285 // Create another keypair for signing/verifying salmon protocol messages.
1286 $sres = Crypto::newKeypair(512);
1287 $sprvkey = $sres['prvkey'];
1288 $spubkey = $sres['pubkey'];
1290 $insert_result = DBA::insert('user', [
1291 'guid' => System::createUUID(),
1292 'username' => $username,
1293 'password' => $new_password_encoded,
1295 'openid' => $openid_url,
1296 'nickname' => $nickname,
1297 'pubkey' => $pubkey,
1298 'prvkey' => $prvkey,
1299 'spubkey' => $spubkey,
1300 'sprvkey' => $sprvkey,
1301 'verified' => $verified,
1302 'blocked' => $blocked,
1303 'language' => $language,
1304 'timezone' => 'UTC',
1305 'register_date' => DateTimeFormat::utcNow(),
1306 'default-location' => ''
1309 if ($insert_result) {
1310 $uid = DBA::lastInsertId();
1311 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1313 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
1317 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
1320 // if somebody clicked submit twice very quickly, they could end up with two accounts
1321 // due to race condition. Remove this one.
1322 $user_count = DBA::count('user', ['nickname' => $nickname]);
1323 if ($user_count > 1) {
1324 DBA::delete('user', ['uid' => $uid]);
1326 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
1329 $insert_result = DBA::insert('profile', [
1331 'name' => $username,
1332 'photo' => self::getAvatarUrl($user),
1333 'thumb' => self::getAvatarUrl($user, Proxy::SIZE_THUMB),
1334 'publish' => $publish,
1335 'net-publish' => $netpublish,
1337 if (!$insert_result) {
1338 DBA::delete('user', ['uid' => $uid]);
1340 throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
1343 // Create the self contact
1344 if (!Contact::createSelfFromUserId($uid)) {
1345 DBA::delete('user', ['uid' => $uid]);
1347 throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
1350 // Create a circle with no members. This allows somebody to use it
1351 // right away as a default circle for new contacts.
1352 $def_gid = Circle::create($uid, DI::l10n()->t('Friends'));
1354 DBA::delete('user', ['uid' => $uid]);
1356 throw new Exception(DI::l10n()->t('An error occurred creating your default contact circle. Please try again.'));
1359 $fields = ['def_gid' => $def_gid];
1360 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
1361 $fields['allow_gid'] = '<' . $def_gid . '>';
1364 DBA::update('user', $fields, ['uid' => $uid]);
1366 $def_gid_groups = Circle::create($uid, DI::l10n()->t('Groups'));
1367 if ($def_gid_groups) {
1368 DI::pConfig()->set($uid, 'system', 'default-group-gid', $def_gid_groups);
1371 // if we have no OpenID photo try to look up an avatar
1372 if (!strlen($photo)) {
1373 $photo = Network::lookupAvatarByEmail($email);
1376 // unless there is no avatar-addon loaded
1377 if (strlen($photo)) {
1378 $photo_failure = false;
1380 $filename = basename($photo);
1381 $curlResult = DI::httpClient()->get($photo, HttpClientAccept::IMAGE);
1382 if ($curlResult->isSuccess()) {
1383 Logger::debug('Got picture', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $photo]);
1384 $img_str = $curlResult->getBody();
1385 $type = $curlResult->getContentType();
1391 $type = Images::getMimeTypeByData($img_str, $photo, $type);
1393 $image = new Image($img_str, $type);
1394 if ($image->isValid()) {
1395 $image->scaleToSquare(300);
1397 $resource_id = Photo::newResource();
1399 // Not using Photo::PROFILE_PHOTOS here, so that it is discovered as translatable string
1400 $profile_album = DI::l10n()->t('Profile Photos');
1402 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 4);
1405 $photo_failure = true;
1408 $image->scaleDown(80);
1410 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 5);
1413 $photo_failure = true;
1416 $image->scaleDown(48);
1418 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 6);
1421 $photo_failure = true;
1424 if (!$photo_failure) {
1425 Photo::update(['profile' => true, 'photo-type' => Photo::USER_AVATAR], ['resource-id' => $resource_id]);
1429 Contact::updateSelfFromUserID($uid, true);
1432 Hook::callAll('register_account', $uid);
1434 self::setRegisterMethodByUserCount();
1436 $return['user'] = $user;
1441 * Update a user entry and distribute the changes if needed
1443 * @param array $fields
1444 * @param integer $uid
1448 public static function update(array $fields, int $uid): bool
1450 if (!DBA::update('user', $fields, ['uid' => $uid])) {
1454 if (Contact::updateSelfFromUserID($uid)) {
1455 Profile::publishUpdate($uid);
1462 * Sets block state for a given user
1464 * @param int $uid The user id
1465 * @param bool $block Block state (default is true)
1467 * @return bool True, if successfully blocked
1471 public static function block(int $uid, bool $block = true): bool
1473 return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
1477 * Allows a registration based on a hash
1479 * @param string $hash
1481 * @return bool True, if the allow was successful
1483 * @throws HTTPException\InternalServerErrorException
1486 public static function allow(string $hash): bool
1488 $register = Register::getByHash($hash);
1489 if (!DBA::isResult($register)) {
1493 $user = User::getById($register['uid']);
1494 if (!DBA::isResult($user)) {
1498 Register::deleteByHash($hash);
1500 DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]);
1502 $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]);
1504 if (DBA::isResult($profile) && $profile['net-publish'] && Search::getGlobalDirectory()) {
1505 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
1506 Worker::add(Worker::PRIORITY_LOW, "Directory", $url);
1509 $l10n = DI::l10n()->withLang($register['language']);
1511 return User::sendRegisterOpenEmail(
1514 DI::config()->get('config', 'sitename'),
1516 ($register['password'] ?? '') ?: 'Sent in a previous email'
1521 * Denys a pending registration
1523 * @param string $hash The hash of the pending user
1525 * This does not have to go through user_remove() and save the nickname
1526 * permanently against re-registration, as the person was not yet
1527 * allowed to have friends on this system
1529 * @return bool True, if the deny was successful
1532 public static function deny(string $hash): bool
1534 $register = Register::getByHash($hash);
1535 if (!DBA::isResult($register)) {
1539 $user = User::getById($register['uid']);
1540 if (!DBA::isResult($user)) {
1544 // Delete the avatar
1545 Photo::delete(['uid' => $register['uid']]);
1547 return DBA::delete('user', ['uid' => $register['uid']]) &&
1548 Register::deleteByHash($register['hash']);
1552 * Creates a new user based on a minimal set and sends an email to this user
1554 * @param string $name The user's name
1555 * @param string $email The user's email address
1556 * @param string $nick The user's nick name
1557 * @param string $lang The user's language (default is english)
1558 * @return bool True, if the user was created successfully
1559 * @throws HTTPException\InternalServerErrorException
1560 * @throws ErrorException
1561 * @throws ImagickException
1563 public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT): bool
1568 throw new HTTPException\InternalServerErrorException('Invalid arguments.');
1571 $result = self::create([
1572 'username' => $name,
1574 'nickname' => $nick,
1579 $user = $result['user'];
1580 $preamble = Strings::deindent(DI::l10n()->t('
1582 the administrator of %2$s has set up an account for you.'));
1583 $body = Strings::deindent(DI::l10n()->t('
1584 The login details are as follows:
1590 You may change your password from your account "Settings" page after logging
1593 Please take a few moments to review the other account settings on that page.
1595 You may also wish to add some basic information to your default profile
1596 (on the "Profiles" page) so that other people can easily find you.
1598 We recommend adding a profile photo, adding some profile "keywords"
1599 (very useful in making new friends) - and perhaps what country you live in;
1600 if you do not wish to be more specific than that.
1602 We fully respect your right to privacy, and none of these items are necessary.
1603 If you are new and do not know anybody here, they may help
1604 you to make some new and interesting friends.
1606 If you ever want to delete your account, you can do so at %1$s/settings/removeme
1608 Thank you and welcome to %4$s.'));
1610 $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename'));
1611 $body = sprintf($body, DI::baseUrl(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename'));
1613 $email = DI::emailer()
1615 ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body)
1617 ->withRecipient($user['email'])
1619 return DI::emailer()->send($email);
1623 * Sends pending registration confirmation email
1625 * @param array $user User record array
1626 * @param string $sitename
1627 * @param string $siteurl
1628 * @param string $password Plaintext password
1629 * @return NULL|boolean from notification() and email() inherited
1630 * @throws HTTPException\InternalServerErrorException
1632 public static function sendRegisterPendingEmail(array $user, string $sitename, string $siteurl, string $password)
1634 $body = Strings::deindent(DI::l10n()->t(
1637 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
1639 Your login details are as follows:
1652 $email = DI::emailer()
1654 ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
1656 ->withRecipient($user['email'])
1658 return DI::emailer()->send($email);
1662 * Sends registration confirmation
1664 * It's here as a function because the mail is sent from different parts
1666 * @param L10n $l10n The used language
1667 * @param array $user User record array
1668 * @param string $sitename
1669 * @param string $siteurl
1670 * @param string $password Plaintext password
1672 * @return NULL|boolean from notification() and email() inherited
1673 * @throws HTTPException\InternalServerErrorException
1675 public static function sendRegisterOpenEmail(L10n $l10n, array $user, string $sitename, string $siteurl, string $password)
1677 $preamble = Strings::deindent($l10n->t(
1680 Thank you for registering at %2$s. Your account has been created.
1685 $body = Strings::deindent($l10n->t(
1687 The login details are as follows:
1693 You may change your password from your account "Settings" page after logging
1696 Please take a few moments to review the other account settings on that page.
1698 You may also wish to add some basic information to your default profile
1699 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1701 We recommend adding a profile photo, adding some profile "keywords" ' . "\x28" . 'very useful
1702 in making new friends' . "\x29" . ' - and perhaps what country you live in; if you do not wish
1703 to be more specific than that.
1705 We fully respect your right to privacy, and none of these items are necessary.
1706 If you are new and do not know anybody here, they may help
1707 you to make some new and interesting friends.
1709 If you ever want to delete your account, you can do so at %3$s/settings/removeme
1711 Thank you and welcome to %2$s.',
1719 $email = DI::emailer()
1721 ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1723 ->withRecipient($user['email'])
1725 return DI::emailer()->send($email);
1729 * @param int $uid user to remove
1731 * @throws HTTPException\InternalServerErrorException
1732 * @throws HTTPException\NotFoundException
1734 public static function remove(int $uid): bool
1737 throw new \InvalidArgumentException('uid needs to be greater than 0');
1740 Logger::notice('Removing user', ['user' => $uid]);
1742 $user = self::getById($uid);
1744 throw new HTTPException\NotFoundException('User not found with uid: ' . $uid);
1747 if (DBA::exists('user', ['parent-uid' => $uid])) {
1748 throw new \RuntimeException(DI::l10n()->t("User with delegates can't be removed, please remove delegate users first"));
1751 Hook::callAll('remove_user', $user);
1753 // save username (actually the nickname as it is guaranteed
1754 // unique), so it cannot be re-registered in the future.
1755 DBA::insert('userd', ['username' => $user['nickname']]);
1757 // Remove all personal settings, especially connector settings
1758 DBA::delete('pconfig', ['uid' => $uid]);
1760 // The user and related data will be deleted in Friendica\Worker\ExpireAndRemoveUsers
1761 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1762 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1764 // Send an update to the directory
1765 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1766 Worker::add(Worker::PRIORITY_LOW, 'Directory', $self['url']);
1768 // Remove the user relevant data
1769 Worker::add(Worker::PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1771 self::setRegisterMethodByUserCount();
1776 * Return all identities to a user
1778 * @param int $uid The user id
1779 * @return array All identities for this user
1781 * Example for a return:
1785 * 'username' => 'maxmuster',
1786 * 'nickname' => 'Max Mustermann'
1790 * 'username' => 'johndoe',
1791 * 'nickname' => 'John Doe'
1796 public static function identities(int $uid): array
1804 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
1805 if (!DBA::isResult($user)) {
1809 if (!$user['parent-uid']) {
1810 // First add our own entry
1812 'uid' => $user['uid'],
1813 'username' => $user['username'],
1814 'nickname' => $user['nickname']
1817 // Then add all the children
1820 ['uid', 'username', 'nickname'],
1821 ['parent-uid' => $user['uid'], 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]
1823 if (DBA::isResult($r)) {
1824 $identities = array_merge($identities, DBA::toArray($r));
1827 // First entry is our parent
1830 ['uid', 'username', 'nickname'],
1831 ['uid' => $user['parent-uid'], 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]
1833 if (DBA::isResult($r)) {
1834 $identities = DBA::toArray($r);
1837 // Then add all siblings
1840 ['uid', 'username', 'nickname'],
1841 ['parent-uid' => $user['parent-uid'], 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]
1843 if (DBA::isResult($r)) {
1844 $identities = array_merge($identities, DBA::toArray($r));
1849 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1851 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1852 WHERE NOT `user`.`account_removed` AND `manage`.`uid` = ?",
1855 if (DBA::isResult($r)) {
1856 $identities = array_merge($identities, DBA::toArray($r));
1863 * Check if the given user id has delegations or is delegated
1868 public static function hasIdentities(int $uid): bool
1874 $user = DBA::selectFirst('user', ['parent-uid'], ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
1875 if (!DBA::isResult($user)) {
1879 if ($user['parent-uid']) {
1883 if (DBA::exists('user', ['parent-uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false])) {
1887 if (DBA::exists('manage', ['uid' => $uid])) {
1895 * Returns statistical information about the current users of this node
1901 public static function getStatistics(): array
1905 'active_users_halfyear' => 0,
1906 'active_users_monthly' => 0,
1907 'active_users_weekly' => 0,
1910 $userStmt = DBA::select('owner-view', ['uid', 'last-activity', 'last-item'],
1911 ["`verified` AND `last-activity` > ? AND NOT `blocked`
1912 AND NOT `account_removed` AND NOT `account_expired`",
1913 DBA::NULL_DATETIME]);
1914 if (!DBA::isResult($userStmt)) {
1918 $halfyear = time() - (180 * 24 * 60 * 60);
1919 $month = time() - (30 * 24 * 60 * 60);
1920 $week = time() - (7 * 24 * 60 * 60);
1922 while ($user = DBA::fetch($userStmt)) {
1923 $statistics['total_users']++;
1925 if ((strtotime($user['last-activity']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1927 $statistics['active_users_halfyear']++;
1930 if ((strtotime($user['last-activity']) > $month) || (strtotime($user['last-item']) > $month)
1932 $statistics['active_users_monthly']++;
1935 if ((strtotime($user['last-activity']) > $week) || (strtotime($user['last-item']) > $week)
1937 $statistics['active_users_weekly']++;
1940 DBA::close($userStmt);
1946 * Get all users of the current node
1948 * @param int $start Start count (Default is 0)
1949 * @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE)
1950 * @param string $type The type of users, which should get (all, blocked, removed)
1951 * @param string $order Order of the user list (Default is 'contact.name')
1952 * @param bool $descending Order direction (Default is ascending)
1953 * @return array|bool The list of the users
1956 public static function getList(int $start = 0, int $count = Pager::ITEMS_PER_PAGE, string $type = 'all', string $order = 'name', bool $descending = false)
1958 $param = ['limit' => [$start, $count], 'order' => [$order => $descending]];
1962 $condition['account_removed'] = false;
1963 $condition['blocked'] = false;
1967 $condition['account_removed'] = false;
1968 $condition['blocked'] = true;
1969 $condition['verified'] = true;
1973 $condition['account_removed'] = true;
1977 return DBA::selectToArray('owner-view', [], $condition, $param);
1981 * Returns a list of lowercase admin email addresses from the comma-separated list in the config
1985 public static function getAdminEmailList(): array
1987 $adminEmails = strtolower(str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1988 if (!$adminEmails) {
1992 return explode(',', $adminEmails);
1996 * Returns the complete list of admin user accounts
1998 * @param array $fields
2002 public static function getAdminList(array $fields = []): array
2005 'email' => self::getAdminEmailList(),
2006 'parent-uid' => null,
2009 'account_removed' => false,
2010 'account_expired' => false,
2013 return DBA::selectToArray('user', $fields, $condition, ['order' => ['uid']]);
2017 * Return a list of admin user accounts where each unique email address appears only once.
2019 * This method is meant for admin notifications that do not need to be sent multiple times to the same email address.
2021 * @param array $fields
2025 public static function getAdminListForEmailing(array $fields = []): array
2027 return array_filter(self::getAdminList($fields), function ($user) {
2028 static $emails = [];
2030 if (in_array($user['email'], $emails)) {
2034 $emails[] = $user['email'];
2040 public static function setRegisterMethodByUserCount()
2042 $max_registered_users = DI::config()->get('config', 'max_registered_users');
2043 if ($max_registered_users <= 0) {
2047 $register_policy = DI::config()->get('config', 'register_policy');
2048 if (!in_array($register_policy, [Module\Register::OPEN, Module\Register::CLOSED])) {
2049 Logger::debug('Unsupported register policy.', ['policy' => $register_policy]);
2053 $users = DBA::count('user', ['blocked' => false, 'account_removed' => false, 'account_expired' => false]);
2054 if (($users >= $max_registered_users) && ($register_policy == Module\Register::OPEN)) {
2055 DI::config()->set('config', 'register_policy', Module\Register::CLOSED);
2056 Logger::notice('Max users reached, registration is closed.', ['users' => $users, 'max' => $max_registered_users]);
2057 } elseif (($users < $max_registered_users) && ($register_policy == Module\Register::CLOSED)) {
2058 DI::config()->set('config', 'register_policy', Module\Register::OPEN);
2059 Logger::notice('Below maximum users, registration is opened.', ['users' => $users, 'max' => $max_registered_users]);
2061 Logger::debug('Unchanged register policy', ['policy' => $register_policy, 'users' => $users, 'max' => $max_registered_users]);