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;
136 * Get the Uri-Id of the system account
140 public static function getSystemUriId(): int
142 $system = self::getSystemAccount();
143 return $system['uri-id'] ?? 0;
147 * Fetch the system account
149 * @return array system account
151 public static function getSystemAccount(): array
153 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
154 if (!DBA::isResult($system)) {
155 self::createSystemAccount();
156 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
157 if (!DBA::isResult($system)) {
162 $system['sprvkey'] = $system['uprvkey'] = $system['prvkey'];
163 $system['spubkey'] = $system['upubkey'] = $system['pubkey'];
164 $system['nickname'] = $system['nick'];
165 $system['page-flags'] = User::PAGE_FLAGS_SOAPBOX;
166 $system['account-type'] = $system['contact-type'];
167 $system['guid'] = '';
168 $system['picdate'] = '';
169 $system['theme'] = '';
170 $system['publish'] = false;
171 $system['net-publish'] = false;
172 $system['hide-friends'] = true;
173 $system['hidewall'] = true;
174 $system['prv_keywords'] = '';
175 $system['pub_keywords'] = '';
176 $system['address'] = '';
177 $system['locality'] = '';
178 $system['region'] = '';
179 $system['postal-code'] = '';
180 $system['country-name'] = '';
181 $system['homepage'] = (string)DI::baseUrl();
182 $system['dob'] = '0000-00-00';
184 // Ensure that the user contains data
185 $user = DBA::selectFirst('user', ['prvkey', 'guid', 'language'], ['uid' => 0]);
186 if (empty($user['prvkey']) || empty($user['guid'])) {
188 'username' => $system['name'],
189 'nickname' => $system['nick'],
190 'register_date' => $system['created'],
191 'pubkey' => $system['pubkey'],
192 'prvkey' => $system['prvkey'],
193 'spubkey' => $system['spubkey'],
194 'sprvkey' => $system['sprvkey'],
195 'guid' => System::createUUID(),
197 'page-flags' => User::PAGE_FLAGS_SOAPBOX,
198 'account-type' => User::ACCOUNT_TYPE_RELAY,
201 DBA::update('user', $fields, ['uid' => 0]);
203 $system['guid'] = $fields['guid'];
205 $system['guid'] = $user['guid'];
206 $system['language'] = $user['language'];
213 * Create the system account
217 private static function createSystemAccount()
219 $system_actor_name = self::getActorName();
220 if (empty($system_actor_name)) {
224 $keys = Crypto::newKeypair(4096);
225 if ($keys === false) {
226 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
231 'created' => DateTimeFormat::utcNow(),
233 'network' => Protocol::ACTIVITYPUB,
234 'name' => 'System Account',
235 'addr' => $system_actor_name . '@' . DI::baseUrl()->getHost(),
236 'nick' => $system_actor_name,
237 'url' => DI::baseUrl() . '/friendica',
238 'pubkey' => $keys['pubkey'],
239 'prvkey' => $keys['prvkey'],
242 'contact-type' => Contact::TYPE_RELAY, // In AP this is translated to 'Application'
243 'name-date' => DateTimeFormat::utcNow(),
244 'uri-date' => DateTimeFormat::utcNow(),
245 'avatar-date' => DateTimeFormat::utcNow(),
247 'baseurl' => DI::baseUrl(),
250 $system['avatar'] = $system['photo'] = Contact::getDefaultAvatar($system, Proxy::SIZE_SMALL);
251 $system['thumb'] = Contact::getDefaultAvatar($system, Proxy::SIZE_THUMB);
252 $system['micro'] = Contact::getDefaultAvatar($system, Proxy::SIZE_MICRO);
253 $system['nurl'] = Strings::normaliseLink($system['url']);
254 $system['gsid'] = GServer::getID($system['baseurl']);
256 Contact::insert($system);
260 * Detect a usable actor name
262 * @return string actor account name
264 public static function getActorName(): string
266 $system_actor_name = DI::config()->get('system', 'actor_name');
267 if (!empty($system_actor_name)) {
268 $self = Contact::selectFirst(['nick'], ['uid' => 0, 'self' => true]);
269 if (!empty($self['nick'])) {
270 if ($self['nick'] != $system_actor_name) {
271 // Reset the actor name to the already used name
272 DI::config()->set('system', 'actor_name', $self['nick']);
273 $system_actor_name = $self['nick'];
276 return $system_actor_name;
279 // List of possible actor names
280 $possible_accounts = ['friendica', 'actor', 'system', 'internal'];
281 foreach ($possible_accounts as $name) {
282 if (!DBA::exists('user', ['nickname' => $name]) && !DBA::exists('userd', ['username' => $name])) {
283 DI::config()->set('system', 'actor_name', $name);
291 * Returns true if a user record exists with the provided id
298 public static function exists(int $uid): bool
300 return DBA::exists('user', ['uid' => $uid]);
304 * @param integer $uid
305 * @param array $fields
306 * @return array|boolean User record if it exists, false otherwise
309 public static function getById(int $uid, array $fields = [])
311 return !empty($uid) ? DBA::selectFirst('user', $fields, ['uid' => $uid]) : [];
315 * Returns a user record based on it's GUID
317 * @param string $guid The guid of the user
318 * @param array $fields The fields to retrieve
319 * @param bool $active True, if only active records are searched
321 * @return array|boolean User record if it exists, false otherwise
324 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
327 $cond = ['guid' => $guid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
329 $cond = ['guid' => $guid];
332 return DBA::selectFirst('user', $fields, $cond);
336 * @param string $nickname
337 * @param array $fields
338 * @return array|boolean User record if it exists, false otherwise
341 public static function getByNickname(string $nickname, array $fields = [])
343 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
347 * Set static settings for community user accounts
349 * @param integer $uid
352 public static function setCommunityUserSettings(int $uid)
354 $user = self::getById($uid, ['account-type', 'page-flags']);
355 if ($user['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
359 DI::pConfig()->set($uid, 'system', 'unlisted', true);
363 'allow_gid' => $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP ? '<' . Circle::FOLLOWERS . '>' : '',
370 User::update($fields, $uid);
372 Profile::update(['hide-friends' => true], $uid);
376 * Returns the user id of a given profile URL
380 * @return integer user id
383 public static function getIdForURL(string $url): int
385 // Avoid database queries when the local node hostname isn't even part of the url.
386 if (!Contact::isLocal($url)) {
390 $self = Contact::selectFirst(['uid'], ['self' => true, 'nurl' => Strings::normaliseLink($url)]);
391 if (!empty($self['uid'])) {
395 $self = Contact::selectFirst(['uid'], ['self' => true, 'addr' => $url]);
396 if (!empty($self['uid'])) {
400 $self = Contact::selectFirst(['uid'], ['self' => true, 'alias' => [$url, Strings::normaliseLink($url)]]);
401 if (!empty($self['uid'])) {
409 * Get a user based on its email
411 * @param string $email
412 * @param array $fields
413 * @return array|boolean User record if it exists, false otherwise
416 public static function getByEmail(string $email, array $fields = [])
418 return DBA::selectFirst('user', $fields, ['email' => $email]);
422 * Fetch the user array of the administrator. The first one if there are several.
424 * @param array $fields
428 public static function getFirstAdmin(array $fields = []) : array
430 if (!empty(DI::config()->get('config', 'admin_nickname'))) {
431 return self::getByNickname(DI::config()->get('config', 'admin_nickname'), $fields);
434 return self::getAdminList()[0] ?? [];
438 * Get owner data by user id
441 * @param boolean $repairMissing Repair the owner data if it's missing
442 * @return boolean|array
445 public static function getOwnerDataById(int $uid, bool $repairMissing = true)
448 return self::getSystemAccount();
451 if (!empty(self::$owner[$uid])) {
452 return self::$owner[$uid];
455 $owner = DBA::selectFirst('owner-view', [], ['uid' => $uid]);
456 if (!DBA::isResult($owner)) {
457 if (!self::exists($uid) || !$repairMissing) {
460 if (!DBA::exists('profile', ['uid' => $uid])) {
461 DBA::insert('profile', ['uid' => $uid]);
463 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
464 Contact::createSelfFromUserId($uid);
466 $owner = self::getOwnerDataById($uid, false);
469 if (empty($owner['nickname'])) {
473 if (!$repairMissing || $owner['account_expired']) {
477 // Check if the returned data is valid, otherwise fix it. See issue #6122
479 // Check for correct url and normalised nurl
480 $url = DI::baseUrl() . '/profile/' . $owner['nickname'];
481 $repair = empty($owner['network']) || ($owner['url'] != $url) || ($owner['nurl'] != Strings::normaliseLink($owner['url']));
484 // Check if "addr" is present and correct
485 $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
486 $repair = ($addr != $owner['addr']) || empty($owner['prvkey']) || empty($owner['pubkey']);
490 // Check if the avatar field is filled and the photo directs to the correct path
491 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
492 if (DBA::isResult($avatar)) {
493 $repair = empty($owner['avatar']) || !strpos($owner['photo'], $avatar['resource-id']);
498 Contact::updateSelfFromUserID($uid);
499 // Return the corrected data and avoid a loop
500 $owner = self::getOwnerDataById($uid, false);
503 self::$owner[$uid] = $owner;
508 * Get owner data by nick name
511 * @return boolean|array
514 public static function getOwnerDataByNick(string $nick)
516 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
518 if (!DBA::isResult($user)) {
522 return self::getOwnerDataById($user['uid']);
526 * Returns the default circle for a given user
528 * @param int $uid User id
530 * @return int circle id
533 public static function getDefaultCircle(int $uid): int
535 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
536 if (DBA::isResult($user)) {
537 $default_circle = $user['def_gid'];
542 return $default_circle;
546 * Returns the default circle for groups for a given user
548 * @param int $uid User id
550 * @return int circle id
553 public static function getDefaultGroupCircle(int $uid): int
555 $default_circle = DI::pConfig()->get($uid, 'system', 'default-group-gid');
556 if (empty($default_circle)) {
557 $default_circle = self::getDefaultCircle($uid);
560 return $default_circle;
564 * Fetch the language code from the given user. If the code is invalid, return the system language
566 * @param integer $uid User-Id
569 public static function getLanguageCode(int $uid): string
571 $owner = self::getOwnerDataById($uid);
572 $languages = DI::l10n()->getAvailableLanguages(true);
573 if (in_array($owner['language'], array_keys($languages))) {
574 $language = $owner['language'];
576 $language = DI::config()->get('system', 'language');
582 * Authenticate a user with a clear text password
584 * Returns the user id associated with a successful password authentication
586 * @param mixed $user_info
587 * @param string $password
588 * @param bool $third_party
589 * @return int User Id if authentication is successful
590 * @throws HTTPException\ForbiddenException
591 * @throws HTTPException\NotFoundException
593 public static function getIdFromPasswordAuthentication($user_info, string $password, bool $third_party = false): int
595 // Addons registered with the "authenticate" hook may create the user on the
596 // fly. `getAuthenticationInfo` will fail if the user doesn't exist yet. If
597 // the user doesn't exist, we should give the addons a chance to create the
598 // user in our database, if applicable, before re-throwing the exception if
601 $user = self::getAuthenticationInfo($user_info);
602 } catch (Exception $e) {
603 $username = (is_string($user_info) ? $user_info : $user_info['nickname'] ?? '');
605 // Addons can create users, and since this 'catch' branch should only
606 // execute if getAuthenticationInfo can't find an existing user, that's
607 // exactly what will happen here. Creating a numeric username would create
608 // ambiguity with user IDs, possibly opening up an attack vector.
609 // So let's be very careful about that.
610 if (empty($username) || is_numeric($username)) {
614 return self::getIdFromAuthenticateHooks($username, $password);
617 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
618 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
619 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
622 } elseif (strpos($user['password'], '$') === false) {
623 //Legacy hash that has not been replaced by a new hash yet
624 if (self::hashPasswordLegacy($password) === $user['password']) {
625 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
629 } elseif (!empty($user['legacy_password'])) {
630 //Legacy hash that has been double-hashed and not replaced by a new hash yet
631 //Warning: `legacy_password` is not necessary in sync with the content of `password`
632 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
633 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
637 } elseif (password_verify($password, $user['password'])) {
639 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
640 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
645 return self::getIdFromAuthenticateHooks($user['nickname'], $password); // throws
648 throw new HTTPException\ForbiddenException(DI::l10n()->t('Login failed'));
652 * Try to obtain a user ID via "authenticate" hook addons
654 * Returns the user id associated with a successful password authentication
656 * @param string $username
657 * @param string $password
658 * @return int User Id if authentication is successful
659 * @throws HTTPException\ForbiddenException
661 public static function getIdFromAuthenticateHooks(string $username, string $password): int
664 'username' => $username,
665 'password' => $password,
666 'authenticated' => 0,
667 'user_record' => null
671 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
672 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
673 * and later addons should not interfere with an earlier one that succeeded.
675 Hook::callAll('authenticate', $addon_auth);
677 if ($addon_auth['authenticated'] && $addon_auth['user_record']) {
678 return $addon_auth['user_record']['uid'];
681 throw new HTTPException\ForbiddenException(DI::l10n()->t('Login failed'));
685 * Returns authentication info from various parameters types
687 * User info can be any of the following:
690 * - User email or username or nickname
691 * - User array with at least the uid and the hashed password
693 * @param mixed $user_info
694 * @return array|null Null if not found/determined
695 * @throws HTTPException\NotFoundException
697 public static function getAuthenticationInfo($user_info)
701 if (is_object($user_info) || is_array($user_info)) {
702 if (is_object($user_info)) {
703 $user = (array) $user_info;
710 || !isset($user['password'])
711 || !isset($user['legacy_password'])
713 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
715 } elseif (is_int($user_info) || is_string($user_info)) {
716 if (is_int($user_info)) {
717 $user = DBA::selectFirst(
719 ['uid', 'nickname', 'password', 'legacy_password'],
723 'account_expired' => 0,
724 'account_removed' => 0,
729 $fields = ['uid', 'nickname', 'password', 'legacy_password'];
731 "(`email` = ? OR `username` = ? OR `nickname` = ?)
732 AND `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`",
733 $user_info, $user_info, $user_info
735 $user = DBA::selectFirst('user', $fields, $condition);
738 if (!DBA::isResult($user)) {
739 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found'));
747 * Update the day of the last activity of the given user
749 * @param integer $uid
752 public static function updateLastActivity(int $uid)
758 $user = User::getById($uid, ['last-activity']);
763 $current_day = DateTimeFormat::utcNow('Y-m-d');
765 if ($user['last-activity'] != $current_day) {
766 User::update(['last-activity' => $current_day], $uid);
767 // Set the last activity for all identities of the user
768 DBA::update('user', ['last-activity' => $current_day], ['parent-uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
773 * Generates a human-readable random password
778 public static function generateNewPassword(): string
780 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
784 * Checks if the provided plaintext password has been exposed or not
786 * @param string $password
790 public static function isPasswordExposed(string $password): bool
792 $cache = new CacheItemPool();
793 $cache->changeConfig([
794 'cacheDirectory' => System::getTempPath() . '/password-exposed-cache/',
798 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
800 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
801 } catch (Exception $e) {
802 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
803 'code' => $e->getCode(),
804 'file' => $e->getFile(),
805 'line' => $e->getLine(),
806 'trace' => $e->getTraceAsString()
814 * Legacy hashing function, kept for password migration purposes
816 * @param string $password
819 private static function hashPasswordLegacy(string $password): string
821 return hash('whirlpool', $password);
825 * Global user password hashing function
827 * @param string $password
831 public static function hashPassword(string $password): string
833 if (!trim($password)) {
834 throw new Exception(DI::l10n()->t('Password can\'t be empty'));
837 return password_hash($password, PASSWORD_DEFAULT);
841 * Allowed characters are a-z, A-Z, 0-9 and special characters except white spaces and accentuated letters.
843 * Password length is limited to 72 characters if the current default password hashing algorithm is Blowfish.
844 * From the manual: "Using the PASSWORD_BCRYPT as the algorithm, will result in the password parameter being
845 * truncated to a maximum length of 72 bytes."
847 * @see https://www.php.net/manual/en/function.password-hash.php#refsect1-function.password-hash-parameters
849 * @param string|null $delimiter Whether the regular expression is meant to be wrapper in delimiter characters
852 public static function getPasswordRegExp(string $delimiter = null): string
854 $allowed_characters = ':!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
857 $allowed_characters = preg_quote($allowed_characters, $delimiter);
860 return '^[a-zA-Z0-9' . $allowed_characters . ']' . (PASSWORD_DEFAULT === PASSWORD_BCRYPT ? '{1,72}' : '+') . '$';
864 * Updates a user row with a new plaintext password
867 * @param string $password
871 public static function updatePassword(int $uid, string $password): bool
873 $password = trim($password);
875 if (empty($password)) {
876 throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
879 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
880 throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
883 if (PASSWORD_DEFAULT === PASSWORD_BCRYPT && strlen($password) > 72) {
884 throw new Exception(DI::l10n()->t('The password length is limited to 72 characters.'));
887 if (!preg_match('/' . self::getPasswordRegExp('/') . '/', $password)) {
888 throw new Exception(DI::l10n()->t("The password can't contain white spaces nor accentuated letters"));
891 return self::updatePasswordHashed($uid, self::hashPassword($password));
895 * Updates a user row with a new hashed password.
896 * Empties the password reset token field just in case.
899 * @param string $password_hashed
903 private static function updatePasswordHashed(int $uid, string $password_hashed): bool
906 'password' => $password_hashed,
908 'pwdreset_time' => null,
909 'legacy_password' => false
911 return DBA::update('user', $fields, ['uid' => $uid]);
915 * Returns if the given uid is valid and in the admin list
922 public static function isSiteAdmin(int $uid): bool
924 return DBA::exists('user', [
926 'email' => self::getAdminEmailList()
931 * Returns if the given uid is valid and a moderator
938 public static function isModerator(int $uid): bool
940 // @todo Replace with a moderator check in the future
941 return self::isSiteAdmin($uid);
945 * Checks if a nickname is in the list of the forbidden nicknames
947 * Check if a nickname is forbidden from registration on the node by the
948 * admin. Forbidden nicknames (e.g. role names) can be configured in the
951 * @param string $nickname The nickname that should be checked
952 * @return boolean True is the nickname is blocked on the node
954 public static function isNicknameBlocked(string $nickname): bool
956 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
957 if (!empty($forbidden_nicknames)) {
958 $forbidden = explode(',', $forbidden_nicknames);
959 $forbidden = array_map('trim', $forbidden);
964 // Add the name of the internal actor to the "forbidden" list
965 $actor_name = self::getActorName();
966 if (!empty($actor_name)) {
967 $forbidden[] = $actor_name;
970 if (empty($forbidden)) {
974 // check if the nickname is in the list of blocked nicknames
975 if (in_array(strtolower($nickname), $forbidden)) {
984 * Get avatar link for given user
987 * @param string $size One of the Proxy::SIZE_* constants
988 * @return string avatar link
991 public static function getAvatarUrl(array $user, string $size = ''): string
993 if (empty($user['nickname'])) {
994 DI::logger()->warning('Missing user nickname key');
997 $url = DI::baseUrl() . '/photo/';
1000 case Proxy::SIZE_MICRO:
1004 case Proxy::SIZE_THUMB:
1017 $photo = Photo::selectFirst(['type', 'created', 'edited', 'updated'], ["scale" => $scale, 'uid' => $user['uid'], 'profile' => true]);
1018 if (!empty($photo)) {
1019 $updated = max($photo['created'], $photo['edited'], $photo['updated']);
1020 $mimetype = $photo['type'];
1023 return $url . $user['nickname'] . Images::getExtensionByMimeType($mimetype) . ($updated ? '?ts=' . strtotime($updated) : '');
1027 * Get banner link for given user
1029 * @param array $user
1030 * @return string banner link
1033 public static function getBannerUrl(array $user): string
1035 if (empty($user['nickname'])) {
1036 DI::logger()->warning('Missing user nickname key');
1039 $url = DI::baseUrl() . '/photo/banner/';
1044 $photo = Photo::selectFirst(['type', 'created', 'edited', 'updated'], ["scale" => 3, 'uid' => $user['uid'], 'photo-type' => Photo::USER_BANNER]);
1045 if (!empty($photo)) {
1046 $updated = max($photo['created'], $photo['edited'], $photo['updated']);
1047 $mimetype = $photo['type'];
1049 // Only for the RC phase: Don't return an image link for the default picture
1053 return $url . $user['nickname'] . Images::getExtensionByMimeType($mimetype) . ($updated ? '?ts=' . strtotime($updated) : '');
1057 * Catch-all user creation function
1059 * Creates a user from the provided data array, either form fields or OpenID.
1060 * Required: { username, nickname, email } or { openid_url }
1062 * Performs the following:
1063 * - Sends to the OpenId auth URL (if relevant)
1064 * - Creates new key pairs for crypto
1065 * - Create self-contact
1066 * - Create profile image
1068 * @param array $data
1070 * @throws ErrorException
1071 * @throws HTTPException\InternalServerErrorException
1072 * @throws ImagickException
1075 public static function create(array $data): array
1077 $return = ['user' => null, 'password' => ''];
1079 $using_invites = DI::config()->get('system', 'invitation_only');
1081 $invite_id = !empty($data['invite_id']) ? trim($data['invite_id']) : '';
1082 $username = !empty($data['username']) ? trim($data['username']) : '';
1083 $nickname = !empty($data['nickname']) ? trim($data['nickname']) : '';
1084 $email = !empty($data['email']) ? trim($data['email']) : '';
1085 $openid_url = !empty($data['openid_url']) ? trim($data['openid_url']) : '';
1086 $photo = !empty($data['photo']) ? trim($data['photo']) : '';
1087 $password = !empty($data['password']) ? trim($data['password']) : '';
1088 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
1089 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
1090 $blocked = !empty($data['blocked']);
1091 $verified = !empty($data['verified']);
1092 $language = !empty($data['language']) ? trim($data['language']) : 'en';
1094 $netpublish = $publish = !empty($data['profile_publish_reg']);
1096 if ($password1 != $confirm) {
1097 throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
1098 } elseif ($password1 != '') {
1099 $password = $password1;
1102 if ($using_invites) {
1104 throw new Exception(DI::l10n()->t('An invitation is required.'));
1107 if (!Register::existsByHash($invite_id)) {
1108 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
1112 /// @todo Check if this part is really needed. We should have fetched all this data in advance
1113 if (empty($username) || empty($email) || empty($nickname)) {
1115 if (!Network::isUrlValid($openid_url)) {
1116 throw new Exception(DI::l10n()->t('Invalid OpenID url'));
1118 $_SESSION['register'] = 1;
1119 $_SESSION['openid'] = $openid_url;
1121 $openid = new LightOpenID(DI::baseUrl()->getHost());
1122 $openid->identity = $openid_url;
1123 $openid->returnUrl = DI::baseUrl() . '/openid';
1124 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
1125 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
1127 $authurl = $openid->authUrl();
1128 } catch (Exception $e) {
1129 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);
1131 System::externalRedirect($authurl);
1135 throw new Exception(DI::l10n()->t('Please enter the required information.'));
1138 if (!Network::isUrlValid($openid_url)) {
1142 // collapse multiple spaces in name
1143 $username = preg_replace('/ +/', ' ', $username);
1145 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
1146 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
1148 if ($username_min_length > $username_max_length) {
1149 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));
1150 $tmp = $username_min_length;
1151 $username_min_length = $username_max_length;
1152 $username_max_length = $tmp;
1155 if (mb_strlen($username) < $username_min_length) {
1156 throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
1159 if (mb_strlen($username) > $username_max_length) {
1160 throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
1163 // So now we are just looking for a space in the display name.
1164 $loose_reg = DI::config()->get('system', 'no_regfullname');
1166 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
1167 if (strpos($username, ' ') === false) {
1168 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
1172 if (!Network::isEmailDomainAllowed($email)) {
1173 throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
1176 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
1177 throw new Exception(DI::l10n()->t('Not a valid email address.'));
1179 if (self::isNicknameBlocked($nickname)) {
1180 throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
1183 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
1184 throw new Exception(DI::l10n()->t('Cannot use that email.'));
1187 // Disallow somebody creating an account using openid that uses the admin email address,
1188 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
1189 if (strlen($openid_url) && in_array(strtolower($email), self::getAdminEmailList())) {
1190 throw new Exception(DI::l10n()->t('Cannot use that email.'));
1193 $nickname = $data['nickname'] = strtolower($nickname);
1195 if (!preg_match('/^[a-z0-9][a-z0-9_]*$/', $nickname)) {
1196 throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
1199 // Check existing and deleted accounts for this nickname.
1201 DBA::exists('user', ['nickname' => $nickname])
1202 || DBA::exists('userd', ['username' => $nickname])
1204 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
1207 $new_password = strlen($password) ? $password : User::generateNewPassword();
1208 $new_password_encoded = self::hashPassword($new_password);
1210 $return['password'] = $new_password;
1212 $keys = Crypto::newKeypair(4096);
1213 if ($keys === false) {
1214 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
1217 $prvkey = $keys['prvkey'];
1218 $pubkey = $keys['pubkey'];
1220 // Create another keypair for signing/verifying salmon protocol messages.
1221 $sres = Crypto::newKeypair(512);
1222 $sprvkey = $sres['prvkey'];
1223 $spubkey = $sres['pubkey'];
1225 $insert_result = DBA::insert('user', [
1226 'guid' => System::createUUID(),
1227 'username' => $username,
1228 'password' => $new_password_encoded,
1230 'openid' => $openid_url,
1231 'nickname' => $nickname,
1232 'pubkey' => $pubkey,
1233 'prvkey' => $prvkey,
1234 'spubkey' => $spubkey,
1235 'sprvkey' => $sprvkey,
1236 'verified' => $verified,
1237 'blocked' => $blocked,
1238 'language' => $language,
1239 'timezone' => 'UTC',
1240 'register_date' => DateTimeFormat::utcNow(),
1241 'default-location' => ''
1244 if ($insert_result) {
1245 $uid = DBA::lastInsertId();
1246 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1248 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
1252 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
1255 // if somebody clicked submit twice very quickly, they could end up with two accounts
1256 // due to race condition. Remove this one.
1257 $user_count = DBA::count('user', ['nickname' => $nickname]);
1258 if ($user_count > 1) {
1259 DBA::delete('user', ['uid' => $uid]);
1261 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
1264 $insert_result = DBA::insert('profile', [
1266 'name' => $username,
1267 'photo' => self::getAvatarUrl($user),
1268 'thumb' => self::getAvatarUrl($user, Proxy::SIZE_THUMB),
1269 'publish' => $publish,
1270 'net-publish' => $netpublish,
1272 if (!$insert_result) {
1273 DBA::delete('user', ['uid' => $uid]);
1275 throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
1278 // Create the self contact
1279 if (!Contact::createSelfFromUserId($uid)) {
1280 DBA::delete('user', ['uid' => $uid]);
1282 throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
1285 // Create a circle with no members. This allows somebody to use it
1286 // right away as a default circle for new contacts.
1287 $def_gid = Circle::create($uid, DI::l10n()->t('Friends'));
1289 DBA::delete('user', ['uid' => $uid]);
1291 throw new Exception(DI::l10n()->t('An error occurred creating your default contact circle. Please try again.'));
1294 $fields = ['def_gid' => $def_gid];
1295 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
1296 $fields['allow_gid'] = '<' . $def_gid . '>';
1299 DBA::update('user', $fields, ['uid' => $uid]);
1301 $def_gid_groups = Circle::create($uid, DI::l10n()->t('Groups'));
1302 if ($def_gid_groups) {
1303 DI::pConfig()->set($uid, 'system', 'default-group-gid', $def_gid_groups);
1306 // if we have no OpenID photo try to look up an avatar
1307 if (!strlen($photo)) {
1308 $photo = Network::lookupAvatarByEmail($email);
1311 // unless there is no avatar-addon loaded
1312 if (strlen($photo)) {
1313 $photo_failure = false;
1315 $filename = basename($photo);
1316 $curlResult = DI::httpClient()->get($photo, HttpClientAccept::IMAGE);
1317 if ($curlResult->isSuccess()) {
1318 Logger::debug('Got picture', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $photo]);
1319 $img_str = $curlResult->getBody();
1320 $type = $curlResult->getContentType();
1326 $type = Images::getMimeTypeByData($img_str, $photo, $type);
1328 $image = new Image($img_str, $type);
1329 if ($image->isValid()) {
1330 $image->scaleToSquare(300);
1332 $resource_id = Photo::newResource();
1334 // Not using Photo::PROFILE_PHOTOS here, so that it is discovered as translatable string
1335 $profile_album = DI::l10n()->t('Profile Photos');
1337 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 4);
1340 $photo_failure = true;
1343 $image->scaleDown(80);
1345 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 5);
1348 $photo_failure = true;
1351 $image->scaleDown(48);
1353 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 6);
1356 $photo_failure = true;
1359 if (!$photo_failure) {
1360 Photo::update(['profile' => true, 'photo-type' => Photo::USER_AVATAR], ['resource-id' => $resource_id]);
1364 Contact::updateSelfFromUserID($uid, true);
1367 Hook::callAll('register_account', $uid);
1369 self::setRegisterMethodByUserCount();
1371 $return['user'] = $user;
1376 * Update a user entry and distribute the changes if needed
1378 * @param array $fields
1379 * @param integer $uid
1383 public static function update(array $fields, int $uid): bool
1385 if (!DBA::update('user', $fields, ['uid' => $uid])) {
1389 if (Contact::updateSelfFromUserID($uid)) {
1390 Profile::publishUpdate($uid);
1397 * Sets block state for a given user
1399 * @param int $uid The user id
1400 * @param bool $block Block state (default is true)
1402 * @return bool True, if successfully blocked
1406 public static function block(int $uid, bool $block = true): bool
1408 return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
1412 * Allows a registration based on a hash
1414 * @param string $hash
1416 * @return bool True, if the allow was successful
1418 * @throws HTTPException\InternalServerErrorException
1421 public static function allow(string $hash): bool
1423 $register = Register::getByHash($hash);
1424 if (!DBA::isResult($register)) {
1428 $user = User::getById($register['uid']);
1429 if (!DBA::isResult($user)) {
1433 Register::deleteByHash($hash);
1435 DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]);
1437 $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]);
1439 if (DBA::isResult($profile) && $profile['net-publish'] && Search::getGlobalDirectory()) {
1440 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
1441 Worker::add(Worker::PRIORITY_LOW, "Directory", $url);
1444 $l10n = DI::l10n()->withLang($register['language']);
1446 return User::sendRegisterOpenEmail(
1449 DI::config()->get('config', 'sitename'),
1451 ($register['password'] ?? '') ?: 'Sent in a previous email'
1456 * Denys a pending registration
1458 * @param string $hash The hash of the pending user
1460 * This does not have to go through user_remove() and save the nickname
1461 * permanently against re-registration, as the person was not yet
1462 * allowed to have friends on this system
1464 * @return bool True, if the deny was successful
1467 public static function deny(string $hash): bool
1469 $register = Register::getByHash($hash);
1470 if (!DBA::isResult($register)) {
1474 $user = User::getById($register['uid']);
1475 if (!DBA::isResult($user)) {
1479 // Delete the avatar
1480 Photo::delete(['uid' => $register['uid']]);
1482 return DBA::delete('user', ['uid' => $register['uid']]) &&
1483 Register::deleteByHash($register['hash']);
1487 * Creates a new user based on a minimal set and sends an email to this user
1489 * @param string $name The user's name
1490 * @param string $email The user's email address
1491 * @param string $nick The user's nick name
1492 * @param string $lang The user's language (default is english)
1493 * @return bool True, if the user was created successfully
1494 * @throws HTTPException\InternalServerErrorException
1495 * @throws ErrorException
1496 * @throws ImagickException
1498 public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT): bool
1503 throw new HTTPException\InternalServerErrorException('Invalid arguments.');
1506 $result = self::create([
1507 'username' => $name,
1509 'nickname' => $nick,
1514 $user = $result['user'];
1515 $preamble = Strings::deindent(DI::l10n()->t('
1517 the administrator of %2$s has set up an account for you.'));
1518 $body = Strings::deindent(DI::l10n()->t('
1519 The login details are as follows:
1525 You may change your password from your account "Settings" page after logging
1528 Please take a few moments to review the other account settings on that page.
1530 You may also wish to add some basic information to your default profile
1531 (on the "Profiles" page) so that other people can easily find you.
1533 We recommend adding a profile photo, adding some profile "keywords"
1534 (very useful in making new friends) - and perhaps what country you live in;
1535 if you do not wish to be more specific than that.
1537 We fully respect your right to privacy, and none of these items are necessary.
1538 If you are new and do not know anybody here, they may help
1539 you to make some new and interesting friends.
1541 If you ever want to delete your account, you can do so at %1$s/settings/removeme
1543 Thank you and welcome to %4$s.'));
1545 $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename'));
1546 $body = sprintf($body, DI::baseUrl(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename'));
1548 $email = DI::emailer()
1550 ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body)
1552 ->withRecipient($user['email'])
1554 return DI::emailer()->send($email);
1558 * Sends pending registration confirmation email
1560 * @param array $user User record array
1561 * @param string $sitename
1562 * @param string $siteurl
1563 * @param string $password Plaintext password
1564 * @return NULL|boolean from notification() and email() inherited
1565 * @throws HTTPException\InternalServerErrorException
1567 public static function sendRegisterPendingEmail(array $user, string $sitename, string $siteurl, string $password)
1569 $body = Strings::deindent(DI::l10n()->t(
1572 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
1574 Your login details are as follows:
1587 $email = DI::emailer()
1589 ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
1591 ->withRecipient($user['email'])
1593 return DI::emailer()->send($email);
1597 * Sends registration confirmation
1599 * It's here as a function because the mail is sent from different parts
1601 * @param L10n $l10n The used language
1602 * @param array $user User record array
1603 * @param string $sitename
1604 * @param string $siteurl
1605 * @param string $password Plaintext password
1607 * @return NULL|boolean from notification() and email() inherited
1608 * @throws HTTPException\InternalServerErrorException
1610 public static function sendRegisterOpenEmail(L10n $l10n, array $user, string $sitename, string $siteurl, string $password)
1612 $preamble = Strings::deindent($l10n->t(
1615 Thank you for registering at %2$s. Your account has been created.
1620 $body = Strings::deindent($l10n->t(
1622 The login details are as follows:
1628 You may change your password from your account "Settings" page after logging
1631 Please take a few moments to review the other account settings on that page.
1633 You may also wish to add some basic information to your default profile
1634 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1636 We recommend adding a profile photo, adding some profile "keywords" ' . "\x28" . 'very useful
1637 in making new friends' . "\x29" . ' - and perhaps what country you live in; if you do not wish
1638 to be more specific than that.
1640 We fully respect your right to privacy, and none of these items are necessary.
1641 If you are new and do not know anybody here, they may help
1642 you to make some new and interesting friends.
1644 If you ever want to delete your account, you can do so at %3$s/settings/removeme
1646 Thank you and welcome to %2$s.',
1654 $email = DI::emailer()
1656 ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1658 ->withRecipient($user['email'])
1660 return DI::emailer()->send($email);
1664 * @param int $uid user to remove
1666 * @throws HTTPException\InternalServerErrorException
1667 * @throws HTTPException\NotFoundException
1669 public static function remove(int $uid): bool
1672 throw new \InvalidArgumentException('uid needs to be greater than 0');
1675 Logger::notice('Removing user', ['user' => $uid]);
1677 $user = self::getById($uid);
1679 throw new HTTPException\NotFoundException('User not found with uid: ' . $uid);
1682 if (DBA::exists('user', ['parent-uid' => $uid])) {
1683 throw new \RuntimeException(DI::l10n()->t("User with delegates can't be removed, please remove delegate users first"));
1686 Hook::callAll('remove_user', $user);
1688 // save username (actually the nickname as it is guaranteed
1689 // unique), so it cannot be re-registered in the future.
1690 DBA::insert('userd', ['username' => $user['nickname']]);
1692 // Remove all personal settings, especially connector settings
1693 DBA::delete('pconfig', ['uid' => $uid]);
1695 // The user and related data will be deleted in Friendica\Worker\ExpireAndRemoveUsers
1696 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1697 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1699 // Send an update to the directory
1700 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1701 Worker::add(Worker::PRIORITY_LOW, 'Directory', $self['url']);
1703 // Remove the user relevant data
1704 Worker::add(Worker::PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1706 self::setRegisterMethodByUserCount();
1711 * Return all identities to a user
1713 * @param int $uid The user id
1714 * @return array All identities for this user
1716 * Example for a return:
1720 * 'username' => 'maxmuster',
1721 * 'nickname' => 'Max Mustermann'
1725 * 'username' => 'johndoe',
1726 * 'nickname' => 'John Doe'
1731 public static function identities(int $uid): array
1739 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
1740 if (!DBA::isResult($user)) {
1744 if (!$user['parent-uid']) {
1745 // First add our own entry
1747 'uid' => $user['uid'],
1748 'username' => $user['username'],
1749 'nickname' => $user['nickname']
1752 // Then add all the children
1755 ['uid', 'username', 'nickname'],
1756 ['parent-uid' => $user['uid'], 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]
1758 if (DBA::isResult($r)) {
1759 $identities = array_merge($identities, DBA::toArray($r));
1762 // First entry is our parent
1765 ['uid', 'username', 'nickname'],
1766 ['uid' => $user['parent-uid'], 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]
1768 if (DBA::isResult($r)) {
1769 $identities = DBA::toArray($r);
1772 // Then add all siblings
1775 ['uid', 'username', 'nickname'],
1776 ['parent-uid' => $user['parent-uid'], 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]
1778 if (DBA::isResult($r)) {
1779 $identities = array_merge($identities, DBA::toArray($r));
1784 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1786 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1787 WHERE NOT `user`.`account_removed` AND `manage`.`uid` = ?",
1790 if (DBA::isResult($r)) {
1791 $identities = array_merge($identities, DBA::toArray($r));
1798 * Check if the given user id has delegations or is delegated
1803 public static function hasIdentities(int $uid): bool
1809 $user = DBA::selectFirst('user', ['parent-uid'], ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
1810 if (!DBA::isResult($user)) {
1814 if ($user['parent-uid']) {
1818 if (DBA::exists('user', ['parent-uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false])) {
1822 if (DBA::exists('manage', ['uid' => $uid])) {
1830 * Returns statistical information about the current users of this node
1836 public static function getStatistics(): array
1840 'active_users_halfyear' => 0,
1841 'active_users_monthly' => 0,
1842 'active_users_weekly' => 0,
1845 $userStmt = DBA::select('owner-view', ['uid', 'last-activity', 'last-item'],
1846 ["`verified` AND `last-activity` > ? AND NOT `blocked`
1847 AND NOT `account_removed` AND NOT `account_expired`",
1848 DBA::NULL_DATETIME]);
1849 if (!DBA::isResult($userStmt)) {
1853 $halfyear = time() - (180 * 24 * 60 * 60);
1854 $month = time() - (30 * 24 * 60 * 60);
1855 $week = time() - (7 * 24 * 60 * 60);
1857 while ($user = DBA::fetch($userStmt)) {
1858 $statistics['total_users']++;
1860 if ((strtotime($user['last-activity']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1862 $statistics['active_users_halfyear']++;
1865 if ((strtotime($user['last-activity']) > $month) || (strtotime($user['last-item']) > $month)
1867 $statistics['active_users_monthly']++;
1870 if ((strtotime($user['last-activity']) > $week) || (strtotime($user['last-item']) > $week)
1872 $statistics['active_users_weekly']++;
1875 DBA::close($userStmt);
1881 * Get all users of the current node
1883 * @param int $start Start count (Default is 0)
1884 * @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE)
1885 * @param string $type The type of users, which should get (all, blocked, removed)
1886 * @param string $order Order of the user list (Default is 'contact.name')
1887 * @param bool $descending Order direction (Default is ascending)
1888 * @return array|bool The list of the users
1891 public static function getList(int $start = 0, int $count = Pager::ITEMS_PER_PAGE, string $type = 'all', string $order = 'name', bool $descending = false)
1893 $param = ['limit' => [$start, $count], 'order' => [$order => $descending]];
1897 $condition['account_removed'] = false;
1898 $condition['blocked'] = false;
1902 $condition['account_removed'] = false;
1903 $condition['blocked'] = true;
1904 $condition['verified'] = true;
1908 $condition['account_removed'] = true;
1912 return DBA::selectToArray('owner-view', [], $condition, $param);
1916 * Returns a list of lowercase admin email addresses from the comma-separated list in the config
1920 public static function getAdminEmailList(): array
1922 $adminEmails = strtolower(str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1923 if (!$adminEmails) {
1927 return explode(',', $adminEmails);
1931 * Returns the complete list of admin user accounts
1933 * @param array $fields
1937 public static function getAdminList(array $fields = []): array
1940 'email' => self::getAdminEmailList(),
1941 'parent-uid' => null,
1944 'account_removed' => false,
1945 'account_expired' => false,
1948 return DBA::selectToArray('user', $fields, $condition, ['order' => ['uid']]);
1952 * Return a list of admin user accounts where each unique email address appears only once.
1954 * This method is meant for admin notifications that do not need to be sent multiple times to the same email address.
1956 * @param array $fields
1960 public static function getAdminListForEmailing(array $fields = []): array
1962 return array_filter(self::getAdminList($fields), function ($user) {
1963 static $emails = [];
1965 if (in_array($user['email'], $emails)) {
1969 $emails[] = $user['email'];
1975 public static function setRegisterMethodByUserCount()
1977 $max_registered_users = DI::config()->get('config', 'max_registered_users');
1978 if ($max_registered_users <= 0) {
1982 $register_policy = DI::config()->get('config', 'register_policy');
1983 if (!in_array($register_policy, [Module\Register::OPEN, Module\Register::CLOSED])) {
1984 Logger::debug('Unsupported register policy.', ['policy' => $register_policy]);
1988 $users = DBA::count('user', ['blocked' => false, 'account_removed' => false, 'account_expired' => false]);
1989 if (($users >= $max_registered_users) && ($register_policy == Module\Register::OPEN)) {
1990 DI::config()->set('config', 'register_policy', Module\Register::CLOSED);
1991 Logger::notice('Max users reached, registration is closed.', ['users' => $users, 'max' => $max_registered_users]);
1992 } elseif (($users < $max_registered_users) && ($register_policy == Module\Register::CLOSED)) {
1993 DI::config()->set('config', 'register_policy', Module\Register::OPEN);
1994 Logger::notice('Below maximum users, registration is opened.', ['users' => $users, 'max' => $max_registered_users]);
1996 Logger::debug('Unchanged register policy', ['policy' => $register_policy, 'users' => $users, 'max' => $max_registered_users]);