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\InternalServerErrorException;
41 use Friendica\Security\TwoFactor\Model\AppSpecificPassword;
42 use Friendica\Network\HTTPException;
43 use Friendica\Object\Image;
44 use Friendica\Protocol\Delivery;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Images;
48 use Friendica\Util\Network;
49 use Friendica\Util\Proxy;
50 use Friendica\Util\Strings;
55 * This class handles User related functions
62 * PAGE_FLAGS_NORMAL is a typical personal profile account
63 * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
64 * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
65 * write access to wall and comments (no email and not included in page owner's ACL lists)
66 * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
70 const PAGE_FLAGS_NORMAL = 0;
71 const PAGE_FLAGS_SOAPBOX = 1;
72 const PAGE_FLAGS_COMMUNITY = 2;
73 const PAGE_FLAGS_FREELOVE = 3;
74 const PAGE_FLAGS_BLOG = 4;
75 const PAGE_FLAGS_PRVGROUP = 5;
83 * ACCOUNT_TYPE_PERSON - the account belongs to a person
84 * Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
86 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
87 * Associated page type: PAGE_FLAGS_SOAPBOX
89 * ACCOUNT_TYPE_NEWS - the account is a news reflector
90 * Associated page type: PAGE_FLAGS_SOAPBOX
92 * ACCOUNT_TYPE_COMMUNITY - the account is community group
93 * Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
95 * ACCOUNT_TYPE_RELAY - the account is a relay
96 * This will only be assigned to contacts, not to user accounts
99 const ACCOUNT_TYPE_PERSON = 0;
100 const ACCOUNT_TYPE_ORGANISATION = 1;
101 const ACCOUNT_TYPE_NEWS = 2;
102 const ACCOUNT_TYPE_COMMUNITY = 3;
103 const ACCOUNT_TYPE_RELAY = 4;
104 const ACCOUNT_TYPE_DELETED = 127;
109 private static $owner;
112 * Returns the numeric account type by their string
114 * @param string $accounttype as string constant
115 * @return int|null Numeric account type - or null when not set
117 public static function getAccountTypeByString(string $accounttype)
119 switch ($accounttype) {
121 return User::ACCOUNT_TYPE_PERSON;
124 return User::ACCOUNT_TYPE_ORGANISATION;
127 return User::ACCOUNT_TYPE_NEWS;
130 return User::ACCOUNT_TYPE_COMMUNITY;
137 * Get the Uri-Id of the system account
141 public static function getSystemUriId(): int
143 $system = self::getSystemAccount();
144 return $system['uri-id'] ?? 0;
148 * Fetch the system account
150 * @return array system account
152 public static function getSystemAccount(): array
154 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
155 if (!DBA::isResult($system)) {
156 self::createSystemAccount();
157 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
158 if (!DBA::isResult($system)) {
163 $system['sprvkey'] = $system['uprvkey'] = $system['prvkey'];
164 $system['spubkey'] = $system['upubkey'] = $system['pubkey'];
165 $system['nickname'] = $system['nick'];
166 $system['page-flags'] = User::PAGE_FLAGS_SOAPBOX;
167 $system['account-type'] = $system['contact-type'];
168 $system['guid'] = '';
169 $system['picdate'] = '';
170 $system['theme'] = '';
171 $system['publish'] = false;
172 $system['net-publish'] = false;
173 $system['hide-friends'] = true;
174 $system['hidewall'] = true;
175 $system['prv_keywords'] = '';
176 $system['pub_keywords'] = '';
177 $system['address'] = '';
178 $system['locality'] = '';
179 $system['region'] = '';
180 $system['postal-code'] = '';
181 $system['country-name'] = '';
182 $system['homepage'] = (string)DI::baseUrl();
183 $system['dob'] = '0000-00-00';
185 // Ensure that the user contains data
186 $user = DBA::selectFirst('user', ['prvkey', 'guid', 'language'], ['uid' => 0]);
187 if (empty($user['prvkey']) || empty($user['guid'])) {
189 'username' => $system['name'],
190 'nickname' => $system['nick'],
191 'register_date' => $system['created'],
192 'pubkey' => $system['pubkey'],
193 'prvkey' => $system['prvkey'],
194 'spubkey' => $system['spubkey'],
195 'sprvkey' => $system['sprvkey'],
196 'guid' => System::createUUID(),
198 'page-flags' => User::PAGE_FLAGS_SOAPBOX,
199 'account-type' => User::ACCOUNT_TYPE_RELAY,
202 DBA::update('user', $fields, ['uid' => 0]);
204 $system['guid'] = $fields['guid'];
206 $system['guid'] = $user['guid'];
207 $system['language'] = $user['language'];
214 * Create the system account
218 private static function createSystemAccount()
220 $system_actor_name = self::getActorName();
221 if (empty($system_actor_name)) {
225 $keys = Crypto::newKeypair(4096);
226 if ($keys === false) {
227 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
232 'created' => DateTimeFormat::utcNow(),
234 'network' => Protocol::ACTIVITYPUB,
235 'name' => 'System Account',
236 'addr' => $system_actor_name . '@' . DI::baseUrl()->getHost(),
237 'nick' => $system_actor_name,
238 'url' => DI::baseUrl() . '/friendica',
239 'pubkey' => $keys['pubkey'],
240 'prvkey' => $keys['prvkey'],
243 'contact-type' => Contact::TYPE_RELAY, // In AP this is translated to 'Application'
244 'name-date' => DateTimeFormat::utcNow(),
245 'uri-date' => DateTimeFormat::utcNow(),
246 'avatar-date' => DateTimeFormat::utcNow(),
248 'baseurl' => DI::baseUrl(),
251 $system['avatar'] = $system['photo'] = Contact::getDefaultAvatar($system, Proxy::SIZE_SMALL);
252 $system['thumb'] = Contact::getDefaultAvatar($system, Proxy::SIZE_THUMB);
253 $system['micro'] = Contact::getDefaultAvatar($system, Proxy::SIZE_MICRO);
254 $system['nurl'] = Strings::normaliseLink($system['url']);
255 $system['gsid'] = GServer::getID($system['baseurl']);
257 Contact::insert($system);
261 * Detect a usable actor name
263 * @return string actor account name
265 public static function getActorName(): string
267 $system_actor_name = DI::config()->get('system', 'actor_name');
268 if (!empty($system_actor_name)) {
269 $self = Contact::selectFirst(['nick'], ['uid' => 0, 'self' => true]);
270 if (!empty($self['nick'])) {
271 if ($self['nick'] != $system_actor_name) {
272 // Reset the actor name to the already used name
273 DI::config()->set('system', 'actor_name', $self['nick']);
274 $system_actor_name = $self['nick'];
277 return $system_actor_name;
280 // List of possible actor names
281 $possible_accounts = ['friendica', 'actor', 'system', 'internal'];
282 foreach ($possible_accounts as $name) {
283 if (!DBA::exists('user', ['nickname' => $name, 'account_removed' => false, 'account_expired' => false]) &&
284 !DBA::exists('userd', ['username' => $name])) {
285 DI::config()->set('system', 'actor_name', $name);
293 * Returns true if a user record exists with the provided id
300 public static function exists(int $uid): bool
302 return DBA::exists('user', ['uid' => $uid]);
306 * @param integer $uid
307 * @param array $fields
308 * @return array|boolean User record if it exists, false otherwise
311 public static function getById(int $uid, array $fields = [])
313 return !empty($uid) ? DBA::selectFirst('user', $fields, ['uid' => $uid]) : [];
317 * Returns a user record based on it's GUID
319 * @param string $guid The guid of the user
320 * @param array $fields The fields to retrieve
321 * @param bool $active True, if only active records are searched
323 * @return array|boolean User record if it exists, false otherwise
326 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
329 $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
331 $cond = ['guid' => $guid];
334 return DBA::selectFirst('user', $fields, $cond);
338 * @param string $nickname
339 * @param array $fields
340 * @return array|boolean User record if it exists, false otherwise
343 public static function getByNickname(string $nickname, array $fields = [])
345 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
349 * Returns the user id of a given profile URL
353 * @return integer user id
356 public static function getIdForURL(string $url): int
358 // Avoid database queries when the local node hostname isn't even part of the url.
359 if (!Contact::isLocal($url)) {
363 $self = Contact::selectFirst(['uid'], ['self' => true, 'nurl' => Strings::normaliseLink($url)]);
364 if (!empty($self['uid'])) {
368 $self = Contact::selectFirst(['uid'], ['self' => true, 'addr' => $url]);
369 if (!empty($self['uid'])) {
373 $self = Contact::selectFirst(['uid'], ['self' => true, 'alias' => [$url, Strings::normaliseLink($url)]]);
374 if (!empty($self['uid'])) {
382 * Get a user based on its email
384 * @param string $email
385 * @param array $fields
386 * @return array|boolean User record if it exists, false otherwise
389 public static function getByEmail(string $email, array $fields = [])
391 return DBA::selectFirst('user', $fields, ['email' => $email]);
395 * Fetch the user array of the administrator. The first one if there are several.
397 * @param array $fields
401 public static function getFirstAdmin(array $fields = []) : array
403 if (!empty(DI::config()->get('config', 'admin_nickname'))) {
404 return self::getByNickname(DI::config()->get('config', 'admin_nickname'), $fields);
407 return self::getAdminList()[0] ?? [];
411 * Get owner data by user id
414 * @param boolean $repairMissing Repair the owner data if it's missing
415 * @return boolean|array
418 public static function getOwnerDataById(int $uid, bool $repairMissing = true)
421 return self::getSystemAccount();
424 if (!empty(self::$owner[$uid])) {
425 return self::$owner[$uid];
428 $owner = DBA::selectFirst('owner-view', [], ['uid' => $uid]);
429 if (!DBA::isResult($owner)) {
430 if (!self::exists($uid) || !$repairMissing) {
433 if (!DBA::exists('profile', ['uid' => $uid])) {
434 DBA::insert('profile', ['uid' => $uid]);
436 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
437 Contact::createSelfFromUserId($uid);
439 $owner = self::getOwnerDataById($uid, false);
442 if (empty($owner['nickname'])) {
446 if (!$repairMissing || $owner['account_expired']) {
450 // Check if the returned data is valid, otherwise fix it. See issue #6122
452 // Check for correct url and normalised nurl
453 $url = DI::baseUrl() . '/profile/' . $owner['nickname'];
454 $repair = empty($owner['network']) || ($owner['url'] != $url) || ($owner['nurl'] != Strings::normaliseLink($owner['url']));
457 // Check if "addr" is present and correct
458 $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
459 $repair = ($addr != $owner['addr']) || empty($owner['prvkey']) || empty($owner['pubkey']);
463 // Check if the avatar field is filled and the photo directs to the correct path
464 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
465 if (DBA::isResult($avatar)) {
466 $repair = empty($owner['avatar']) || !strpos($owner['photo'], $avatar['resource-id']);
471 Contact::updateSelfFromUserID($uid);
472 // Return the corrected data and avoid a loop
473 $owner = self::getOwnerDataById($uid, false);
476 self::$owner[$uid] = $owner;
481 * Get owner data by nick name
484 * @return boolean|array
487 public static function getOwnerDataByNick(string $nick)
489 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
491 if (!DBA::isResult($user)) {
495 return self::getOwnerDataById($user['uid']);
499 * Returns the default circle for a given user
501 * @param int $uid User id
503 * @return int circle id
506 public static function getDefaultCircle(int $uid): int
508 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
509 if (DBA::isResult($user)) {
510 $default_circle = $user['def_gid'];
515 return $default_circle;
519 * Returns the default circle for groups for a given user
521 * @param int $uid User id
523 * @return int circle id
526 public static function getDefaultGroupCircle(int $uid): int
528 $default_circle = DI::pConfig()->get($uid, 'system', 'default-group-gid');
529 if (empty($default_circle)) {
530 $default_circle = self::getDefaultCircle($uid);
533 return $default_circle;
537 * Fetch the language code from the given user. If the code is invalid, return the system language
539 * @param integer $uid User-Id
542 public static function getLanguageCode(int $uid): string
544 $owner = self::getOwnerDataById($uid);
545 $languages = DI::l10n()->getAvailableLanguages(true);
546 if (in_array($owner['language'], array_keys($languages))) {
547 $language = $owner['language'];
549 $language = DI::config()->get('system', 'language');
555 * Authenticate a user with a clear text password
557 * Returns the user id associated with a successful password authentication
559 * @param mixed $user_info
560 * @param string $password
561 * @param bool $third_party
562 * @return int User Id if authentication is successful
563 * @throws HTTPException\ForbiddenException
564 * @throws HTTPException\NotFoundException
566 public static function getIdFromPasswordAuthentication($user_info, string $password, bool $third_party = false): int
568 // Addons registered with the "authenticate" hook may create the user on the
569 // fly. `getAuthenticationInfo` will fail if the user doesn't exist yet. If
570 // the user doesn't exist, we should give the addons a chance to create the
571 // user in our database, if applicable, before re-throwing the exception if
574 $user = self::getAuthenticationInfo($user_info);
575 } catch (Exception $e) {
576 $username = (is_string($user_info) ? $user_info : $user_info['nickname'] ?? '');
578 // Addons can create users, and since this 'catch' branch should only
579 // execute if getAuthenticationInfo can't find an existing user, that's
580 // exactly what will happen here. Creating a numeric username would create
581 // ambiguity with user IDs, possibly opening up an attack vector.
582 // So let's be very careful about that.
583 if (empty($username) || is_numeric($username)) {
587 return self::getIdFromAuthenticateHooks($username, $password);
590 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
591 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
592 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
595 } elseif (strpos($user['password'], '$') === false) {
596 //Legacy hash that has not been replaced by a new hash yet
597 if (self::hashPasswordLegacy($password) === $user['password']) {
598 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
602 } elseif (!empty($user['legacy_password'])) {
603 //Legacy hash that has been double-hashed and not replaced by a new hash yet
604 //Warning: `legacy_password` is not necessary in sync with the content of `password`
605 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
606 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
610 } elseif (password_verify($password, $user['password'])) {
612 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
613 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
618 return self::getIdFromAuthenticateHooks($user['nickname'], $password); // throws
621 throw new HTTPException\ForbiddenException(DI::l10n()->t('Login failed'));
625 * Try to obtain a user ID via "authenticate" hook addons
627 * Returns the user id associated with a successful password authentication
629 * @param string $username
630 * @param string $password
631 * @return int User Id if authentication is successful
632 * @throws HTTPException\ForbiddenException
634 public static function getIdFromAuthenticateHooks(string $username, string $password): int
637 'username' => $username,
638 'password' => $password,
639 'authenticated' => 0,
640 'user_record' => null
644 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
645 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
646 * and later addons should not interfere with an earlier one that succeeded.
648 Hook::callAll('authenticate', $addon_auth);
650 if ($addon_auth['authenticated'] && $addon_auth['user_record']) {
651 return $addon_auth['user_record']['uid'];
654 throw new HTTPException\ForbiddenException(DI::l10n()->t('Login failed'));
658 * Returns authentication info from various parameters types
660 * User info can be any of the following:
663 * - User email or username or nickname
664 * - User array with at least the uid and the hashed password
666 * @param mixed $user_info
667 * @return array|null Null if not found/determined
668 * @throws HTTPException\NotFoundException
670 public static function getAuthenticationInfo($user_info)
674 if (is_object($user_info) || is_array($user_info)) {
675 if (is_object($user_info)) {
676 $user = (array) $user_info;
683 || !isset($user['password'])
684 || !isset($user['legacy_password'])
686 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
688 } elseif (is_int($user_info) || is_string($user_info)) {
689 if (is_int($user_info)) {
690 $user = DBA::selectFirst(
692 ['uid', 'nickname', 'password', 'legacy_password'],
696 'account_expired' => 0,
697 'account_removed' => 0,
702 $fields = ['uid', 'nickname', 'password', 'legacy_password'];
704 "(`email` = ? OR `username` = ? OR `nickname` = ?)
705 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
706 $user_info, $user_info, $user_info
708 $user = DBA::selectFirst('user', $fields, $condition);
711 if (!DBA::isResult($user)) {
712 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found'));
720 * Update the day of the last activity of the given user
722 * @param integer $uid
725 public static function updateLastActivity(int $uid)
731 $user = User::getById($uid, ['last-activity']);
736 $current_day = DateTimeFormat::utcNow('Y-m-d');
738 if ($user['last-activity'] != $current_day) {
739 User::update(['last-activity' => $current_day], $uid);
740 // Set the last activity for all identities of the user
741 DBA::update('user', ['last-activity' => $current_day], ['parent-uid' => $uid, 'account_removed' => false]);
746 * Generates a human-readable random password
751 public static function generateNewPassword(): string
753 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
757 * Checks if the provided plaintext password has been exposed or not
759 * @param string $password
763 public static function isPasswordExposed(string $password): bool
765 $cache = new CacheItemPool();
766 $cache->changeConfig([
767 'cacheDirectory' => System::getTempPath() . '/password-exposed-cache/',
771 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
773 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
774 } catch (Exception $e) {
775 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
776 'code' => $e->getCode(),
777 'file' => $e->getFile(),
778 'line' => $e->getLine(),
779 'trace' => $e->getTraceAsString()
787 * Legacy hashing function, kept for password migration purposes
789 * @param string $password
792 private static function hashPasswordLegacy(string $password): string
794 return hash('whirlpool', $password);
798 * Global user password hashing function
800 * @param string $password
804 public static function hashPassword(string $password): string
806 if (!trim($password)) {
807 throw new Exception(DI::l10n()->t('Password can\'t be empty'));
810 return password_hash($password, PASSWORD_DEFAULT);
814 * Allowed characters are a-z, A-Z, 0-9 and special characters except white spaces and accentuated letters.
816 * Password length is limited to 72 characters if the current default password hashing algorithm is Blowfish.
817 * From the manual: "Using the PASSWORD_BCRYPT as the algorithm, will result in the password parameter being
818 * truncated to a maximum length of 72 bytes."
820 * @see https://www.php.net/manual/en/function.password-hash.php#refsect1-function.password-hash-parameters
822 * @param string|null $delimiter Whether the regular expression is meant to be wrapper in delimiter characters
825 public static function getPasswordRegExp(string $delimiter = null): string
827 $allowed_characters = ':!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
830 $allowed_characters = preg_quote($allowed_characters, $delimiter);
833 return '^[a-zA-Z0-9' . $allowed_characters . ']' . (PASSWORD_DEFAULT === PASSWORD_BCRYPT ? '{1,72}' : '+') . '$';
837 * Updates a user row with a new plaintext password
840 * @param string $password
844 public static function updatePassword(int $uid, string $password): bool
846 $password = trim($password);
848 if (empty($password)) {
849 throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
852 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
853 throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
856 if (PASSWORD_DEFAULT === PASSWORD_BCRYPT && strlen($password) > 72) {
857 throw new Exception(DI::l10n()->t('The password length is limited to 72 characters.'));
860 if (!preg_match('/' . self::getPasswordRegExp('/') . '/', $password)) {
861 throw new Exception(DI::l10n()->t("The password can't contain white spaces nor accentuated letters"));
864 return self::updatePasswordHashed($uid, self::hashPassword($password));
868 * Updates a user row with a new hashed password.
869 * Empties the password reset token field just in case.
872 * @param string $password_hashed
876 private static function updatePasswordHashed(int $uid, string $password_hashed): bool
879 'password' => $password_hashed,
881 'pwdreset_time' => null,
882 'legacy_password' => false
884 return DBA::update('user', $fields, ['uid' => $uid]);
888 * Returns if the given uid is valid and in the admin list
895 public static function isSiteAdmin(int $uid): bool
897 return DBA::exists('user', [
899 'email' => self::getAdminEmailList()
904 * Returns if the given uid is valid and a moderator
911 public static function isModerator(int $uid): bool
913 // @todo Replace with a moderator check in the future
914 return self::isSiteAdmin($uid);
918 * Checks if a nickname is in the list of the forbidden nicknames
920 * Check if a nickname is forbidden from registration on the node by the
921 * admin. Forbidden nicknames (e.g. role names) can be configured in the
924 * @param string $nickname The nickname that should be checked
925 * @return boolean True is the nickname is blocked on the node
927 public static function isNicknameBlocked(string $nickname): bool
929 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
930 if (!empty($forbidden_nicknames)) {
931 $forbidden = explode(',', $forbidden_nicknames);
932 $forbidden = array_map('trim', $forbidden);
937 // Add the name of the internal actor to the "forbidden" list
938 $actor_name = self::getActorName();
939 if (!empty($actor_name)) {
940 $forbidden[] = $actor_name;
943 if (empty($forbidden)) {
947 // check if the nickname is in the list of blocked nicknames
948 if (in_array(strtolower($nickname), $forbidden)) {
957 * Get avatar link for given user
960 * @param string $size One of the Proxy::SIZE_* constants
961 * @return string avatar link
964 public static function getAvatarUrl(array $user, string $size = ''): string
966 if (empty($user['nickname'])) {
967 DI::logger()->warning('Missing user nickname key', ['trace' => System::callstack(20)]);
970 $url = DI::baseUrl() . '/photo/';
973 case Proxy::SIZE_MICRO:
977 case Proxy::SIZE_THUMB:
990 $photo = Photo::selectFirst(['type', 'created', 'edited', 'updated'], ["scale" => $scale, 'uid' => $user['uid'], 'profile' => true]);
991 if (!empty($photo)) {
992 $updated = max($photo['created'], $photo['edited'], $photo['updated']);
993 $mimetype = $photo['type'];
996 return $url . $user['nickname'] . Images::getExtensionByMimeType($mimetype) . ($updated ? '?ts=' . strtotime($updated) : '');
1000 * Get banner link for given user
1002 * @param array $user
1003 * @return string banner link
1006 public static function getBannerUrl(array $user): string
1008 if (empty($user['nickname'])) {
1009 DI::logger()->warning('Missing user nickname key', ['trace' => System::callstack(20)]);
1012 $url = DI::baseUrl() . '/photo/banner/';
1017 $photo = Photo::selectFirst(['type', 'created', 'edited', 'updated'], ["scale" => 3, 'uid' => $user['uid'], 'photo-type' => Photo::USER_BANNER]);
1018 if (!empty($photo)) {
1019 $updated = max($photo['created'], $photo['edited'], $photo['updated']);
1020 $mimetype = $photo['type'];
1022 // Only for the RC phase: Don't return an image link for the default picture
1026 return $url . $user['nickname'] . Images::getExtensionByMimeType($mimetype) . ($updated ? '?ts=' . strtotime($updated) : '');
1030 * Catch-all user creation function
1032 * Creates a user from the provided data array, either form fields or OpenID.
1033 * Required: { username, nickname, email } or { openid_url }
1035 * Performs the following:
1036 * - Sends to the OpenId auth URL (if relevant)
1037 * - Creates new key pairs for crypto
1038 * - Create self-contact
1039 * - Create profile image
1041 * @param array $data
1043 * @throws ErrorException
1044 * @throws HTTPException\InternalServerErrorException
1045 * @throws ImagickException
1048 public static function create(array $data): array
1050 $return = ['user' => null, 'password' => ''];
1052 $using_invites = DI::config()->get('system', 'invitation_only');
1054 $invite_id = !empty($data['invite_id']) ? trim($data['invite_id']) : '';
1055 $username = !empty($data['username']) ? trim($data['username']) : '';
1056 $nickname = !empty($data['nickname']) ? trim($data['nickname']) : '';
1057 $email = !empty($data['email']) ? trim($data['email']) : '';
1058 $openid_url = !empty($data['openid_url']) ? trim($data['openid_url']) : '';
1059 $photo = !empty($data['photo']) ? trim($data['photo']) : '';
1060 $password = !empty($data['password']) ? trim($data['password']) : '';
1061 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
1062 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
1063 $blocked = !empty($data['blocked']);
1064 $verified = !empty($data['verified']);
1065 $language = !empty($data['language']) ? trim($data['language']) : 'en';
1067 $netpublish = $publish = !empty($data['profile_publish_reg']);
1069 if ($password1 != $confirm) {
1070 throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
1071 } elseif ($password1 != '') {
1072 $password = $password1;
1075 if ($using_invites) {
1077 throw new Exception(DI::l10n()->t('An invitation is required.'));
1080 if (!Register::existsByHash($invite_id)) {
1081 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
1085 /// @todo Check if this part is really needed. We should have fetched all this data in advance
1086 if (empty($username) || empty($email) || empty($nickname)) {
1088 if (!Network::isUrlValid($openid_url)) {
1089 throw new Exception(DI::l10n()->t('Invalid OpenID url'));
1091 $_SESSION['register'] = 1;
1092 $_SESSION['openid'] = $openid_url;
1094 $openid = new LightOpenID(DI::baseUrl()->getHost());
1095 $openid->identity = $openid_url;
1096 $openid->returnUrl = DI::baseUrl() . '/openid';
1097 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
1098 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
1100 $authurl = $openid->authUrl();
1101 } catch (Exception $e) {
1102 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);
1104 System::externalRedirect($authurl);
1108 throw new Exception(DI::l10n()->t('Please enter the required information.'));
1111 if (!Network::isUrlValid($openid_url)) {
1115 // collapse multiple spaces in name
1116 $username = preg_replace('/ +/', ' ', $username);
1118 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
1119 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
1121 if ($username_min_length > $username_max_length) {
1122 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));
1123 $tmp = $username_min_length;
1124 $username_min_length = $username_max_length;
1125 $username_max_length = $tmp;
1128 if (mb_strlen($username) < $username_min_length) {
1129 throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
1132 if (mb_strlen($username) > $username_max_length) {
1133 throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
1136 // So now we are just looking for a space in the full name.
1137 $loose_reg = DI::config()->get('system', 'no_regfullname');
1139 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
1140 if (strpos($username, ' ') === false) {
1141 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
1145 if (!Network::isEmailDomainAllowed($email)) {
1146 throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
1149 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
1150 throw new Exception(DI::l10n()->t('Not a valid email address.'));
1152 if (self::isNicknameBlocked($nickname)) {
1153 throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
1156 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
1157 throw new Exception(DI::l10n()->t('Cannot use that email.'));
1160 // Disallow somebody creating an account using openid that uses the admin email address,
1161 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
1162 if (strlen($openid_url) && in_array(strtolower($email), self::getAdminEmailList())) {
1163 throw new Exception(DI::l10n()->t('Cannot use that email.'));
1166 $nickname = $data['nickname'] = strtolower($nickname);
1168 if (!preg_match('/^[a-z0-9][a-z0-9_]*$/', $nickname)) {
1169 throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
1172 // Check existing and deleted accounts for this nickname.
1174 DBA::exists('user', ['nickname' => $nickname])
1175 || DBA::exists('userd', ['username' => $nickname])
1177 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
1180 $new_password = strlen($password) ? $password : User::generateNewPassword();
1181 $new_password_encoded = self::hashPassword($new_password);
1183 $return['password'] = $new_password;
1185 $keys = Crypto::newKeypair(4096);
1186 if ($keys === false) {
1187 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
1190 $prvkey = $keys['prvkey'];
1191 $pubkey = $keys['pubkey'];
1193 // Create another keypair for signing/verifying salmon protocol messages.
1194 $sres = Crypto::newKeypair(512);
1195 $sprvkey = $sres['prvkey'];
1196 $spubkey = $sres['pubkey'];
1198 $insert_result = DBA::insert('user', [
1199 'guid' => System::createUUID(),
1200 'username' => $username,
1201 'password' => $new_password_encoded,
1203 'openid' => $openid_url,
1204 'nickname' => $nickname,
1205 'pubkey' => $pubkey,
1206 'prvkey' => $prvkey,
1207 'spubkey' => $spubkey,
1208 'sprvkey' => $sprvkey,
1209 'verified' => $verified,
1210 'blocked' => $blocked,
1211 'language' => $language,
1212 'timezone' => 'UTC',
1213 'register_date' => DateTimeFormat::utcNow(),
1214 'default-location' => ''
1217 if ($insert_result) {
1218 $uid = DBA::lastInsertId();
1219 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1221 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
1225 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
1228 // if somebody clicked submit twice very quickly, they could end up with two accounts
1229 // due to race condition. Remove this one.
1230 $user_count = DBA::count('user', ['nickname' => $nickname]);
1231 if ($user_count > 1) {
1232 DBA::delete('user', ['uid' => $uid]);
1234 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
1237 $insert_result = DBA::insert('profile', [
1239 'name' => $username,
1240 'photo' => self::getAvatarUrl($user),
1241 'thumb' => self::getAvatarUrl($user, Proxy::SIZE_THUMB),
1242 'publish' => $publish,
1243 'net-publish' => $netpublish,
1245 if (!$insert_result) {
1246 DBA::delete('user', ['uid' => $uid]);
1248 throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
1251 // Create the self contact
1252 if (!Contact::createSelfFromUserId($uid)) {
1253 DBA::delete('user', ['uid' => $uid]);
1255 throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
1258 // Create a circle with no members. This allows somebody to use it
1259 // right away as a default circle for new contacts.
1260 $def_gid = Circle::create($uid, DI::l10n()->t('Friends'));
1262 DBA::delete('user', ['uid' => $uid]);
1264 throw new Exception(DI::l10n()->t('An error occurred creating your default contact circle. Please try again.'));
1267 $fields = ['def_gid' => $def_gid];
1268 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
1269 $fields['allow_gid'] = '<' . $def_gid . '>';
1272 DBA::update('user', $fields, ['uid' => $uid]);
1274 $def_gid_groups = Circle::create($uid, DI::l10n()->t('Groups'));
1275 if ($def_gid_groups) {
1276 DI::pConfig()->set($uid, 'system', 'default-group-gid', $def_gid_groups);
1279 // if we have no OpenID photo try to look up an avatar
1280 if (!strlen($photo)) {
1281 $photo = Network::lookupAvatarByEmail($email);
1284 // unless there is no avatar-addon loaded
1285 if (strlen($photo)) {
1286 $photo_failure = false;
1288 $filename = basename($photo);
1289 $curlResult = DI::httpClient()->get($photo, HttpClientAccept::IMAGE);
1290 if ($curlResult->isSuccess()) {
1291 Logger::debug('Got picture', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $photo]);
1292 $img_str = $curlResult->getBody();
1293 $type = $curlResult->getContentType();
1299 $type = Images::getMimeTypeByData($img_str, $photo, $type);
1301 $image = new Image($img_str, $type);
1302 if ($image->isValid()) {
1303 $image->scaleToSquare(300);
1305 $resource_id = Photo::newResource();
1307 // Not using Photo::PROFILE_PHOTOS here, so that it is discovered as translatable string
1308 $profile_album = DI::l10n()->t('Profile Photos');
1310 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 4);
1313 $photo_failure = true;
1316 $image->scaleDown(80);
1318 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 5);
1321 $photo_failure = true;
1324 $image->scaleDown(48);
1326 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 6);
1329 $photo_failure = true;
1332 if (!$photo_failure) {
1333 Photo::update(['profile' => true, 'photo-type' => Photo::USER_AVATAR], ['resource-id' => $resource_id]);
1337 Contact::updateSelfFromUserID($uid, true);
1340 Hook::callAll('register_account', $uid);
1342 self::setRegisterMethodByUserCount();
1344 $return['user'] = $user;
1349 * Update a user entry and distribute the changes if needed
1351 * @param array $fields
1352 * @param integer $uid
1356 public static function update(array $fields, int $uid): bool
1358 if (!DBA::update('user', $fields, ['uid' => $uid])) {
1362 if (Contact::updateSelfFromUserID($uid)) {
1363 Profile::publishUpdate($uid);
1370 * Sets block state for a given user
1372 * @param int $uid The user id
1373 * @param bool $block Block state (default is true)
1375 * @return bool True, if successfully blocked
1379 public static function block(int $uid, bool $block = true): bool
1381 return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
1385 * Allows a registration based on a hash
1387 * @param string $hash
1389 * @return bool True, if the allow was successful
1391 * @throws HTTPException\InternalServerErrorException
1394 public static function allow(string $hash): bool
1396 $register = Register::getByHash($hash);
1397 if (!DBA::isResult($register)) {
1401 $user = User::getById($register['uid']);
1402 if (!DBA::isResult($user)) {
1406 Register::deleteByHash($hash);
1408 DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]);
1410 $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]);
1412 if (DBA::isResult($profile) && $profile['net-publish'] && Search::getGlobalDirectory()) {
1413 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
1414 Worker::add(Worker::PRIORITY_LOW, "Directory", $url);
1417 $l10n = DI::l10n()->withLang($register['language']);
1419 return User::sendRegisterOpenEmail(
1422 DI::config()->get('config', 'sitename'),
1424 ($register['password'] ?? '') ?: 'Sent in a previous email'
1429 * Denys a pending registration
1431 * @param string $hash The hash of the pending user
1433 * This does not have to go through user_remove() and save the nickname
1434 * permanently against re-registration, as the person was not yet
1435 * allowed to have friends on this system
1437 * @return bool True, if the deny was successful
1440 public static function deny(string $hash): bool
1442 $register = Register::getByHash($hash);
1443 if (!DBA::isResult($register)) {
1447 $user = User::getById($register['uid']);
1448 if (!DBA::isResult($user)) {
1452 // Delete the avatar
1453 Photo::delete(['uid' => $register['uid']]);
1455 return DBA::delete('user', ['uid' => $register['uid']]) &&
1456 Register::deleteByHash($register['hash']);
1460 * Creates a new user based on a minimal set and sends an email to this user
1462 * @param string $name The user's name
1463 * @param string $email The user's email address
1464 * @param string $nick The user's nick name
1465 * @param string $lang The user's language (default is english)
1466 * @return bool True, if the user was created successfully
1467 * @throws HTTPException\InternalServerErrorException
1468 * @throws ErrorException
1469 * @throws ImagickException
1471 public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT): bool
1476 throw new HTTPException\InternalServerErrorException('Invalid arguments.');
1479 $result = self::create([
1480 'username' => $name,
1482 'nickname' => $nick,
1487 $user = $result['user'];
1488 $preamble = Strings::deindent(DI::l10n()->t('
1490 the administrator of %2$s has set up an account for you.'));
1491 $body = Strings::deindent(DI::l10n()->t('
1492 The login details are as follows:
1498 You may change your password from your account "Settings" page after logging
1501 Please take a few moments to review the other account settings on that page.
1503 You may also wish to add some basic information to your default profile
1504 (on the "Profiles" page) so that other people can easily find you.
1506 We recommend setting your full name, adding a profile photo,
1507 adding some profile "keywords" (very useful in making new friends) - and
1508 perhaps what country you live in; if you do not wish to be more specific
1511 We fully respect your right to privacy, and none of these items are necessary.
1512 If you are new and do not know anybody here, they may help
1513 you to make some new and interesting friends.
1515 If you ever want to delete your account, you can do so at %1$s/settings/removeme
1517 Thank you and welcome to %4$s.'));
1519 $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename'));
1520 $body = sprintf($body, DI::baseUrl(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename'));
1522 $email = DI::emailer()
1524 ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body)
1526 ->withRecipient($user['email'])
1528 return DI::emailer()->send($email);
1532 * Sends pending registration confirmation email
1534 * @param array $user User record array
1535 * @param string $sitename
1536 * @param string $siteurl
1537 * @param string $password Plaintext password
1538 * @return NULL|boolean from notification() and email() inherited
1539 * @throws HTTPException\InternalServerErrorException
1541 public static function sendRegisterPendingEmail(array $user, string $sitename, string $siteurl, string $password)
1543 $body = Strings::deindent(DI::l10n()->t(
1546 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
1548 Your login details are as follows:
1561 $email = DI::emailer()
1563 ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
1565 ->withRecipient($user['email'])
1567 return DI::emailer()->send($email);
1571 * Sends registration confirmation
1573 * It's here as a function because the mail is sent from different parts
1575 * @param L10n $l10n The used language
1576 * @param array $user User record array
1577 * @param string $sitename
1578 * @param string $siteurl
1579 * @param string $password Plaintext password
1581 * @return NULL|boolean from notification() and email() inherited
1582 * @throws HTTPException\InternalServerErrorException
1584 public static function sendRegisterOpenEmail(L10n $l10n, array $user, string $sitename, string $siteurl, string $password)
1586 $preamble = Strings::deindent($l10n->t(
1589 Thank you for registering at %2$s. Your account has been created.
1594 $body = Strings::deindent($l10n->t(
1596 The login details are as follows:
1602 You may change your password from your account "Settings" page after logging
1605 Please take a few moments to review the other account settings on that page.
1607 You may also wish to add some basic information to your default profile
1608 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1610 We recommend setting your full name, adding a profile photo,
1611 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
1612 perhaps what country you live in; if you do not wish to be more specific
1615 We fully respect your right to privacy, and none of these items are necessary.
1616 If you are new and do not know anybody here, they may help
1617 you to make some new and interesting friends.
1619 If you ever want to delete your account, you can do so at %3$s/settings/removeme
1621 Thank you and welcome to %2$s.',
1629 $email = DI::emailer()
1631 ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1633 ->withRecipient($user['email'])
1635 return DI::emailer()->send($email);
1639 * @param int $uid user to remove
1641 * @throws HTTPException\InternalServerErrorException
1643 public static function remove(int $uid): bool
1649 Logger::notice('Removing user', ['user' => $uid]);
1651 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1653 Hook::callAll('remove_user', $user);
1655 // save username (actually the nickname as it is guaranteed
1656 // unique), so it cannot be re-registered in the future.
1657 DBA::insert('userd', ['username' => $user['nickname']]);
1659 // Remove all personal settings, especially connector settings
1660 DBA::delete('pconfig', ['uid' => $uid]);
1662 // The user and related data will be deleted in Friendica\Worker\ExpireAndRemoveUsers
1663 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1664 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1666 // Send an update to the directory
1667 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1668 Worker::add(Worker::PRIORITY_LOW, 'Directory', $self['url']);
1670 // Remove the user relevant data
1671 Worker::add(Worker::PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1673 self::setRegisterMethodByUserCount();
1678 * Return all identities to a user
1680 * @param int $uid The user id
1681 * @return array All identities for this user
1683 * Example for a return:
1687 * 'username' => 'maxmuster',
1688 * 'nickname' => 'Max Mustermann'
1692 * 'username' => 'johndoe',
1693 * 'nickname' => 'John Doe'
1698 public static function identities(int $uid): array
1706 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1707 if (!DBA::isResult($user)) {
1711 if (!$user['parent-uid']) {
1712 // First add our own entry
1714 'uid' => $user['uid'],
1715 'username' => $user['username'],
1716 'nickname' => $user['nickname']
1719 // Then add all the children
1722 ['uid', 'username', 'nickname'],
1723 ['parent-uid' => $user['uid'], 'account_removed' => false]
1725 if (DBA::isResult($r)) {
1726 $identities = array_merge($identities, DBA::toArray($r));
1729 // First entry is our parent
1732 ['uid', 'username', 'nickname'],
1733 ['uid' => $user['parent-uid'], 'account_removed' => false]
1735 if (DBA::isResult($r)) {
1736 $identities = DBA::toArray($r);
1739 // Then add all siblings
1742 ['uid', 'username', 'nickname'],
1743 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1745 if (DBA::isResult($r)) {
1746 $identities = array_merge($identities, DBA::toArray($r));
1751 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1753 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1754 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1757 if (DBA::isResult($r)) {
1758 $identities = array_merge($identities, DBA::toArray($r));
1765 * Check if the given user id has delegations or is delegated
1770 public static function hasIdentities(int $uid): bool
1776 $user = DBA::selectFirst('user', ['parent-uid'], ['uid' => $uid, 'account_removed' => false]);
1777 if (!DBA::isResult($user)) {
1781 if ($user['parent-uid']) {
1785 if (DBA::exists('user', ['parent-uid' => $uid, 'account_removed' => false])) {
1789 if (DBA::exists('manage', ['uid' => $uid])) {
1797 * Returns statistical information about the current users of this node
1803 public static function getStatistics(): array
1807 'active_users_halfyear' => 0,
1808 'active_users_monthly' => 0,
1809 'active_users_weekly' => 0,
1812 $userStmt = DBA::select('owner-view', ['uid', 'last-activity', 'last-item'],
1813 ["`verified` AND `last-activity` > ? AND NOT `blocked`
1814 AND NOT `account_removed` AND NOT `account_expired`",
1815 DBA::NULL_DATETIME]);
1816 if (!DBA::isResult($userStmt)) {
1820 $halfyear = time() - (180 * 24 * 60 * 60);
1821 $month = time() - (30 * 24 * 60 * 60);
1822 $week = time() - (7 * 24 * 60 * 60);
1824 while ($user = DBA::fetch($userStmt)) {
1825 $statistics['total_users']++;
1827 if ((strtotime($user['last-activity']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1829 $statistics['active_users_halfyear']++;
1832 if ((strtotime($user['last-activity']) > $month) || (strtotime($user['last-item']) > $month)
1834 $statistics['active_users_monthly']++;
1837 if ((strtotime($user['last-activity']) > $week) || (strtotime($user['last-item']) > $week)
1839 $statistics['active_users_weekly']++;
1842 DBA::close($userStmt);
1848 * Get all users of the current node
1850 * @param int $start Start count (Default is 0)
1851 * @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE)
1852 * @param string $type The type of users, which should get (all, blocked, removed)
1853 * @param string $order Order of the user list (Default is 'contact.name')
1854 * @param bool $descending Order direction (Default is ascending)
1855 * @return array|bool The list of the users
1858 public static function getList(int $start = 0, int $count = Pager::ITEMS_PER_PAGE, string $type = 'all', string $order = 'name', bool $descending = false)
1860 $param = ['limit' => [$start, $count], 'order' => [$order => $descending]];
1864 $condition['account_removed'] = false;
1865 $condition['blocked'] = false;
1869 $condition['account_removed'] = false;
1870 $condition['blocked'] = true;
1871 $condition['verified'] = true;
1875 $condition['account_removed'] = true;
1879 return DBA::selectToArray('owner-view', [], $condition, $param);
1883 * Returns a list of lowercase admin email addresses from the comma-separated list in the config
1887 public static function getAdminEmailList(): array
1889 $adminEmails = strtolower(str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1890 if (!$adminEmails) {
1894 return explode(',', $adminEmails);
1898 * Returns the complete list of admin user accounts
1900 * @param array $fields
1904 public static function getAdminList(array $fields = []): array
1907 'email' => self::getAdminEmailList(),
1908 'parent-uid' => null,
1911 'account_removed' => false,
1912 'account_expired' => false,
1915 return DBA::selectToArray('user', $fields, $condition, ['order' => ['uid']]);
1919 * Return a list of admin user accounts where each unique email address appears only once.
1921 * This method is meant for admin notifications that do not need to be sent multiple times to the same email address.
1923 * @param array $fields
1927 public static function getAdminListForEmailing(array $fields = []): array
1929 return array_filter(self::getAdminList($fields), function ($user) {
1930 static $emails = [];
1932 if (in_array($user['email'], $emails)) {
1936 $emails[] = $user['email'];
1942 public static function setRegisterMethodByUserCount()
1944 $max_registered_users = DI::config()->get('config', 'max_registered_users');
1945 if ($max_registered_users <= 0) {
1949 $register_policy = DI::config()->get('config', 'register_policy');
1950 if (!in_array($register_policy, [Module\Register::OPEN, Module\Register::CLOSED])) {
1951 Logger::debug('Unsupported register policy.', ['policy' => $register_policy]);
1955 $users = DBA::count('user', ['blocked' => false, 'account_removed' => false, 'account_expired' => false]);
1956 if (($users >= $max_registered_users) && ($register_policy == Module\Register::OPEN)) {
1957 DI::config()->set('config', 'register_policy', Module\Register::CLOSED);
1958 Logger::notice('Max users reached, registration is closed.', ['users' => $users, 'max' => $max_registered_users]);
1959 } elseif (($users < $max_registered_users) && ($register_policy == Module\Register::CLOSED)) {
1960 DI::config()->set('config', 'register_policy', Module\Register::OPEN);
1961 Logger::notice('Below maximum users, registration is opened.', ['users' => $users, 'max' => $max_registered_users]);
1963 Logger::debug('Unchanged register policy', ['policy' => $register_policy, 'users' => $users, 'max' => $max_registered_users]);