3 * @copyright Copyright (C) 2020, Friendica
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\System;
34 use Friendica\Core\Worker;
35 use Friendica\Database\DBA;
37 use Friendica\Model\TwoFactor\AppSpecificPassword;
38 use Friendica\Network\HTTPException;
39 use Friendica\Object\Image;
40 use Friendica\Util\Crypto;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Images;
43 use Friendica\Util\Network;
44 use Friendica\Util\Strings;
45 use Friendica\Worker\Delivery;
50 * This class handles User related functions
57 * PAGE_FLAGS_NORMAL is a typical personal profile account
58 * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
59 * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
60 * write access to wall and comments (no email and not included in page owner's ACL lists)
61 * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
65 const PAGE_FLAGS_NORMAL = 0;
66 const PAGE_FLAGS_SOAPBOX = 1;
67 const PAGE_FLAGS_COMMUNITY = 2;
68 const PAGE_FLAGS_FREELOVE = 3;
69 const PAGE_FLAGS_BLOG = 4;
70 const PAGE_FLAGS_PRVGROUP = 5;
78 * ACCOUNT_TYPE_PERSON - the account belongs to a person
79 * Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
81 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
82 * Associated page type: PAGE_FLAGS_SOAPBOX
84 * ACCOUNT_TYPE_NEWS - the account is a news reflector
85 * Associated page type: PAGE_FLAGS_SOAPBOX
87 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
88 * Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
90 * ACCOUNT_TYPE_RELAY - the account is a relay
91 * This will only be assigned to contacts, not to user accounts
94 const ACCOUNT_TYPE_PERSON = 0;
95 const ACCOUNT_TYPE_ORGANISATION = 1;
96 const ACCOUNT_TYPE_NEWS = 2;
97 const ACCOUNT_TYPE_COMMUNITY = 3;
98 const ACCOUNT_TYPE_RELAY = 4;
103 private static $owner;
106 * Returns the numeric account type by their string
108 * @param string $accounttype as string constant
109 * @return int|null Numeric account type - or null when not set
111 public static function getAccountTypeByString(string $accounttype)
113 switch ($accounttype) {
115 return User::ACCOUNT_TYPE_PERSON;
117 return User::ACCOUNT_TYPE_ORGANISATION;
119 return User::ACCOUNT_TYPE_NEWS;
121 return User::ACCOUNT_TYPE_COMMUNITY;
129 * Fetch the system account
131 * @return array system account
133 public static function getSystemAccount()
135 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
136 if (!DBA::isResult($system)) {
137 self::createSystemAccount();
138 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
139 if (!DBA::isResult($system)) {
144 $system['sprvkey'] = $system['uprvkey'] = $system['prvkey'];
145 $system['spubkey'] = $system['upubkey'] = $system['pubkey'];
146 $system['nickname'] = $system['nick'];
151 * Create the system account
155 private static function createSystemAccount()
157 $system_actor_name = self::getActorName();
158 if (empty($system_actor_name)) {
162 $keys = Crypto::newKeypair(4096);
163 if ($keys === false) {
164 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
169 $system['created'] = DateTimeFormat::utcNow();
170 $system['self'] = true;
171 $system['network'] = Protocol::ACTIVITYPUB;
172 $system['name'] = 'System Account';
173 $system['addr'] = $system_actor_name . '@' . DI::baseUrl()->getHostname();
174 $system['nick'] = $system_actor_name;
175 $system['avatar'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
176 $system['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
177 $system['thumb'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_THUMB;
178 $system['micro'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_MICRO;
179 $system['url'] = DI::baseUrl() . '/friendica';
180 $system['nurl'] = Strings::normaliseLink($system['url']);
181 $system['pubkey'] = $keys['pubkey'];
182 $system['prvkey'] = $keys['prvkey'];
183 $system['blocked'] = 0;
184 $system['pending'] = 0;
185 $system['contact-type'] = Contact::TYPE_RELAY; // In AP this is translated to 'Application'
186 $system['name-date'] = DateTimeFormat::utcNow();
187 $system['uri-date'] = DateTimeFormat::utcNow();
188 $system['avatar-date'] = DateTimeFormat::utcNow();
189 $system['closeness'] = 0;
190 $system['baseurl'] = DI::baseUrl();
191 $system['gsid'] = GServer::getID($system['baseurl']);
192 DBA::insert('contact', $system);
196 * Detect a usable actor name
198 * @return string actor account name
200 public static function getActorName()
202 $system_actor_name = DI::config()->get('system', 'actor_name');
203 if (!empty($system_actor_name)) {
204 $self = Contact::selectFirst(['nick'], ['uid' => 0, 'self' => true]);
205 if (!empty($self['nick'])) {
206 if ($self['nick'] != $system_actor_name) {
207 // Reset the actor name to the already used name
208 DI::config()->set('system', 'actor_name', $self['nick']);
209 $system_actor_name = $self['nick'];
212 return $system_actor_name;
215 // List of possible actor names
216 $possible_accounts = ['friendica', 'actor', 'system', 'internal'];
217 foreach ($possible_accounts as $name) {
218 if (!DBA::exists('user', ['nickname' => $name, 'account_removed' => false, 'expire']) &&
219 !DBA::exists('userd', ['username' => $name])) {
220 DI::config()->set('system', 'actor_name', $name);
228 * Returns true if a user record exists with the provided id
230 * @param integer $uid
234 public static function exists($uid)
236 return DBA::exists('user', ['uid' => $uid]);
240 * @param integer $uid
241 * @param array $fields
242 * @return array|boolean User record if it exists, false otherwise
245 public static function getById($uid, array $fields = [])
247 return DBA::selectFirst('user', $fields, ['uid' => $uid]);
251 * Returns a user record based on it's GUID
253 * @param string $guid The guid of the user
254 * @param array $fields The fields to retrieve
255 * @param bool $active True, if only active records are searched
257 * @return array|boolean User record if it exists, false otherwise
260 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
263 $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
265 $cond = ['guid' => $guid];
268 return DBA::selectFirst('user', $fields, $cond);
272 * @param string $nickname
273 * @param array $fields
274 * @return array|boolean User record if it exists, false otherwise
277 public static function getByNickname($nickname, array $fields = [])
279 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
283 * Returns the user id of a given profile URL
287 * @return integer user id
290 public static function getIdForURL(string $url)
292 // Avoid any database requests when the hostname isn't even part of the url.
293 if (!strpos($url, DI::baseUrl()->getHostname())) {
297 $self = Contact::selectFirst(['uid'], ['self' => true, 'nurl' => Strings::normaliseLink($url)]);
298 if (!empty($self['uid'])) {
302 $self = Contact::selectFirst(['uid'], ['self' => true, 'addr' => $url]);
303 if (!empty($self['uid'])) {
307 $self = Contact::selectFirst(['uid'], ['self' => true, 'alias' => [$url, Strings::normaliseLink($url)]]);
308 if (!empty($self['uid'])) {
316 * Get a user based on its email
318 * @param string $email
319 * @param array $fields
321 * @return array|boolean User record if it exists, false otherwise
325 public static function getByEmail($email, array $fields = [])
327 return DBA::selectFirst('user', $fields, ['email' => $email]);
331 * Fetch the user array of the administrator. The first one if there are several.
333 * @param array $fields
336 public static function getFirstAdmin(array $fields = [])
338 if (!empty(DI::config()->get('config', 'admin_nickname'))) {
339 return self::getByNickname(DI::config()->get('config', 'admin_nickname'), $fields);
340 } elseif (!empty(DI::config()->get('config', 'admin_email'))) {
341 $adminList = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
342 return self::getByEmail($adminList[0], $fields);
349 * Get owner data by user id
352 * @param boolean $check_valid Test if data is invalid and correct it
353 * @return boolean|array
356 public static function getOwnerDataById(int $uid, bool $check_valid = true)
359 return self::getSystemAccount();
362 if (!empty(self::$owner[$uid])) {
363 return self::$owner[$uid];
366 $owner = DBA::selectFirst('owner-view', [], ['uid' => $uid]);
367 if (!DBA::isResult($owner)) {
368 if (!DBA::exists('user', ['uid' => $uid]) || !$check_valid) {
371 Contact::createSelfFromUserId($uid);
372 $owner = self::getOwnerDataById($uid, false);
375 if (empty($owner['nickname'])) {
383 // Check if the returned data is valid, otherwise fix it. See issue #6122
385 // Check for correct url and normalised nurl
386 $url = DI::baseUrl() . '/profile/' . $owner['nickname'];
387 $repair = ($owner['url'] != $url) || ($owner['nurl'] != Strings::normaliseLink($owner['url']));
390 // Check if "addr" is present and correct
391 $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
392 $repair = ($addr != $owner['addr']) || empty($owner['prvkey']) || empty($owner['pubkey']);
396 // Check if the avatar field is filled and the photo directs to the correct path
397 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
398 if (DBA::isResult($avatar)) {
399 $repair = empty($owner['avatar']) || !strpos($owner['photo'], $avatar['resource-id']);
404 Contact::updateSelfFromUserID($uid);
405 // Return the corrected data and avoid a loop
406 $owner = self::getOwnerDataById($uid, false);
409 self::$owner[$uid] = $owner;
414 * Get owner data by nick name
417 * @return boolean|array
420 public static function getOwnerDataByNick($nick)
422 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
424 if (!DBA::isResult($user)) {
428 return self::getOwnerDataById($user['uid']);
432 * Returns the default group for a given user and network
434 * @param int $uid User id
435 * @param string $network network name
437 * @return int group id
440 public static function getDefaultGroup($uid, $network = '')
444 if ($network == Protocol::OSTATUS) {
445 $default_group = DI::pConfig()->get($uid, "ostatus", "default_group");
448 if ($default_group != 0) {
449 return $default_group;
452 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
454 if (DBA::isResult($user)) {
455 $default_group = $user["def_gid"];
458 return $default_group;
463 * Authenticate a user with a clear text password
465 * @param mixed $user_info
466 * @param string $password
467 * @param bool $third_party
468 * @return int|boolean
469 * @deprecated since version 3.6
470 * @see User::getIdFromPasswordAuthentication()
472 public static function authenticate($user_info, $password, $third_party = false)
475 return self::getIdFromPasswordAuthentication($user_info, $password, $third_party);
476 } catch (Exception $ex) {
482 * Authenticate a user with a clear text password
484 * Returns the user id associated with a successful password authentication
486 * @param mixed $user_info
487 * @param string $password
488 * @param bool $third_party
489 * @return int User Id if authentication is successful
490 * @throws HTTPException\ForbiddenException
491 * @throws HTTPException\NotFoundException
493 public static function getIdFromPasswordAuthentication($user_info, $password, $third_party = false)
495 $user = self::getAuthenticationInfo($user_info);
497 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
498 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
499 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
502 } elseif (strpos($user['password'], '$') === false) {
503 //Legacy hash that has not been replaced by a new hash yet
504 if (self::hashPasswordLegacy($password) === $user['password']) {
505 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
509 } elseif (!empty($user['legacy_password'])) {
510 //Legacy hash that has been double-hashed and not replaced by a new hash yet
511 //Warning: `legacy_password` is not necessary in sync with the content of `password`
512 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
513 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
517 } elseif (password_verify($password, $user['password'])) {
519 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
520 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
526 throw new HTTPException\ForbiddenException(DI::l10n()->t('Login failed'));
530 * Returns authentication info from various parameters types
532 * User info can be any of the following:
535 * - User email or username or nickname
536 * - User array with at least the uid and the hashed password
538 * @param mixed $user_info
540 * @throws HTTPException\NotFoundException
542 private static function getAuthenticationInfo($user_info)
546 if (is_object($user_info) || is_array($user_info)) {
547 if (is_object($user_info)) {
548 $user = (array) $user_info;
555 || !isset($user['password'])
556 || !isset($user['legacy_password'])
558 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
560 } elseif (is_int($user_info) || is_string($user_info)) {
561 if (is_int($user_info)) {
562 $user = DBA::selectFirst(
564 ['uid', 'password', 'legacy_password'],
568 'account_expired' => 0,
569 'account_removed' => 0,
574 $fields = ['uid', 'password', 'legacy_password'];
576 "(`email` = ? OR `username` = ? OR `nickname` = ?)
577 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
578 $user_info, $user_info, $user_info
580 $user = DBA::selectFirst('user', $fields, $condition);
583 if (!DBA::isResult($user)) {
584 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found'));
592 * Generates a human-readable random password
597 public static function generateNewPassword()
599 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
603 * Checks if the provided plaintext password has been exposed or not
605 * @param string $password
609 public static function isPasswordExposed($password)
611 $cache = new CacheItemPool();
612 $cache->changeConfig([
613 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
617 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
619 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
620 } catch (Exception $e) {
621 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
622 'code' => $e->getCode(),
623 'file' => $e->getFile(),
624 'line' => $e->getLine(),
625 'trace' => $e->getTraceAsString()
633 * Legacy hashing function, kept for password migration purposes
635 * @param string $password
638 private static function hashPasswordLegacy($password)
640 return hash('whirlpool', $password);
644 * Global user password hashing function
646 * @param string $password
650 public static function hashPassword($password)
652 if (!trim($password)) {
653 throw new Exception(DI::l10n()->t('Password can\'t be empty'));
656 return password_hash($password, PASSWORD_DEFAULT);
660 * Updates a user row with a new plaintext password
663 * @param string $password
667 public static function updatePassword($uid, $password)
669 $password = trim($password);
671 if (empty($password)) {
672 throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
675 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
676 throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
679 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
681 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
682 throw new Exception(DI::l10n()->t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
685 return self::updatePasswordHashed($uid, self::hashPassword($password));
689 * Updates a user row with a new hashed password.
690 * Empties the password reset token field just in case.
693 * @param string $pasword_hashed
697 private static function updatePasswordHashed($uid, $pasword_hashed)
700 'password' => $pasword_hashed,
702 'pwdreset_time' => null,
703 'legacy_password' => false
705 return DBA::update('user', $fields, ['uid' => $uid]);
709 * Checks if a nickname is in the list of the forbidden nicknames
711 * Check if a nickname is forbidden from registration on the node by the
712 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
715 * @param string $nickname The nickname that should be checked
716 * @return boolean True is the nickname is blocked on the node
718 public static function isNicknameBlocked($nickname)
720 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
721 if (!empty($forbidden_nicknames)) {
722 $forbidden = explode(',', $forbidden_nicknames);
723 $forbidden = array_map('trim', $forbidden);
728 // Add the name of the internal actor to the "forbidden" list
729 $actor_name = self::getActorName();
730 if (!empty($actor_name)) {
731 $forbidden[] = $actor_name;
734 if (empty($forbidden)) {
738 // check if the nickname is in the list of blocked nicknames
739 if (in_array(strtolower($nickname), $forbidden)) {
748 * Catch-all user creation function
750 * Creates a user from the provided data array, either form fields or OpenID.
751 * Required: { username, nickname, email } or { openid_url }
753 * Performs the following:
754 * - Sends to the OpenId auth URL (if relevant)
755 * - Creates new key pairs for crypto
756 * - Create self-contact
757 * - Create profile image
761 * @throws ErrorException
762 * @throws HTTPException\InternalServerErrorException
763 * @throws ImagickException
766 public static function create(array $data)
768 $return = ['user' => null, 'password' => ''];
770 $using_invites = DI::config()->get('system', 'invitation_only');
772 $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
773 $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
774 $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
775 $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
776 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
777 $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
778 $password = !empty($data['password']) ? trim($data['password']) : '';
779 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
780 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
781 $blocked = !empty($data['blocked']);
782 $verified = !empty($data['verified']);
783 $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
785 $netpublish = $publish = !empty($data['profile_publish_reg']);
787 if ($password1 != $confirm) {
788 throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
789 } elseif ($password1 != '') {
790 $password = $password1;
793 if ($using_invites) {
795 throw new Exception(DI::l10n()->t('An invitation is required.'));
798 if (!Register::existsByHash($invite_id)) {
799 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
803 /// @todo Check if this part is really needed. We should have fetched all this data in advance
804 if (empty($username) || empty($email) || empty($nickname)) {
806 if (!Network::isUrlValid($openid_url)) {
807 throw new Exception(DI::l10n()->t('Invalid OpenID url'));
809 $_SESSION['register'] = 1;
810 $_SESSION['openid'] = $openid_url;
812 $openid = new LightOpenID(DI::baseUrl()->getHostname());
813 $openid->identity = $openid_url;
814 $openid->returnUrl = DI::baseUrl() . '/openid';
815 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
816 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
818 $authurl = $openid->authUrl();
819 } catch (Exception $e) {
820 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.') . EOL . EOL . DI::l10n()->t('The error message was:') . $e->getMessage(), 0, $e);
822 System::externalRedirect($authurl);
826 throw new Exception(DI::l10n()->t('Please enter the required information.'));
829 if (!Network::isUrlValid($openid_url)) {
833 // collapse multiple spaces in name
834 $username = preg_replace('/ +/', ' ', $username);
836 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
837 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
839 if ($username_min_length > $username_max_length) {
840 Logger::log(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), Logger::WARNING);
841 $tmp = $username_min_length;
842 $username_min_length = $username_max_length;
843 $username_max_length = $tmp;
846 if (mb_strlen($username) < $username_min_length) {
847 throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
850 if (mb_strlen($username) > $username_max_length) {
851 throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
854 // So now we are just looking for a space in the full name.
855 $loose_reg = DI::config()->get('system', 'no_regfullname');
857 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
858 if (strpos($username, ' ') === false) {
859 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
863 if (!Network::isEmailDomainAllowed($email)) {
864 throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
867 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
868 throw new Exception(DI::l10n()->t('Not a valid email address.'));
870 if (self::isNicknameBlocked($nickname)) {
871 throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
874 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
875 throw new Exception(DI::l10n()->t('Cannot use that email.'));
878 // Disallow somebody creating an account using openid that uses the admin email address,
879 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
880 if (DI::config()->get('config', 'admin_email') && strlen($openid_url)) {
881 $adminlist = explode(',', str_replace(' ', '', strtolower(DI::config()->get('config', 'admin_email'))));
882 if (in_array(strtolower($email), $adminlist)) {
883 throw new Exception(DI::l10n()->t('Cannot use that email.'));
887 $nickname = $data['nickname'] = strtolower($nickname);
889 if (!preg_match('/^[a-z0-9][a-z0-9_]*$/', $nickname)) {
890 throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
893 // Check existing and deleted accounts for this nickname.
895 DBA::exists('user', ['nickname' => $nickname])
896 || DBA::exists('userd', ['username' => $nickname])
898 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
901 $new_password = strlen($password) ? $password : User::generateNewPassword();
902 $new_password_encoded = self::hashPassword($new_password);
904 $return['password'] = $new_password;
906 $keys = Crypto::newKeypair(4096);
907 if ($keys === false) {
908 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
911 $prvkey = $keys['prvkey'];
912 $pubkey = $keys['pubkey'];
914 // Create another keypair for signing/verifying salmon protocol messages.
915 $sres = Crypto::newKeypair(512);
916 $sprvkey = $sres['prvkey'];
917 $spubkey = $sres['pubkey'];
919 $insert_result = DBA::insert('user', [
920 'guid' => System::createUUID(),
921 'username' => $username,
922 'password' => $new_password_encoded,
924 'openid' => $openid_url,
925 'nickname' => $nickname,
928 'spubkey' => $spubkey,
929 'sprvkey' => $sprvkey,
930 'verified' => $verified,
931 'blocked' => $blocked,
932 'language' => $language,
934 'register_date' => DateTimeFormat::utcNow(),
935 'default-location' => ''
938 if ($insert_result) {
939 $uid = DBA::lastInsertId();
940 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
942 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
946 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
949 // if somebody clicked submit twice very quickly, they could end up with two accounts
950 // due to race condition. Remove this one.
951 $user_count = DBA::count('user', ['nickname' => $nickname]);
952 if ($user_count > 1) {
953 DBA::delete('user', ['uid' => $uid]);
955 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
958 $insert_result = DBA::insert('profile', [
961 'photo' => DI::baseUrl() . "/photo/profile/{$uid}.jpg",
962 'thumb' => DI::baseUrl() . "/photo/avatar/{$uid}.jpg",
963 'publish' => $publish,
964 'net-publish' => $netpublish,
966 if (!$insert_result) {
967 DBA::delete('user', ['uid' => $uid]);
969 throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
972 // Create the self contact
973 if (!Contact::createSelfFromUserId($uid)) {
974 DBA::delete('user', ['uid' => $uid]);
976 throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
979 // Create a group with no members. This allows somebody to use it
980 // right away as a default group for new contacts.
981 $def_gid = Group::create($uid, DI::l10n()->t('Friends'));
983 DBA::delete('user', ['uid' => $uid]);
985 throw new Exception(DI::l10n()->t('An error occurred creating your default contact group. Please try again.'));
988 $fields = ['def_gid' => $def_gid];
989 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
990 $fields['allow_gid'] = '<' . $def_gid . '>';
993 DBA::update('user', $fields, ['uid' => $uid]);
995 // if we have no OpenID photo try to look up an avatar
996 if (!strlen($photo)) {
997 $photo = Network::lookupAvatarByEmail($email);
1000 // unless there is no avatar-addon loaded
1001 if (strlen($photo)) {
1002 $photo_failure = false;
1004 $filename = basename($photo);
1005 $curlResult = DI::httpRequest()->get($photo, true);
1006 if ($curlResult->isSuccess()) {
1007 $img_str = $curlResult->getBody();
1008 $type = $curlResult->getContentType();
1014 $type = Images::getMimeTypeByData($img_str, $photo, $type);
1016 $Image = new Image($img_str, $type);
1017 if ($Image->isValid()) {
1018 $Image->scaleToSquare(300);
1020 $resource_id = Photo::newResource();
1022 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 4);
1025 $photo_failure = true;
1028 $Image->scaleDown(80);
1030 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 5);
1033 $photo_failure = true;
1036 $Image->scaleDown(48);
1038 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 6);
1041 $photo_failure = true;
1044 if (!$photo_failure) {
1045 Photo::update(['profile' => 1], ['resource-id' => $resource_id]);
1050 Hook::callAll('register_account', $uid);
1052 $return['user'] = $user;
1057 * Sets block state for a given user
1059 * @param int $uid The user id
1060 * @param bool $block Block state (default is true)
1062 * @return bool True, if successfully blocked
1066 public static function block(int $uid, bool $block = true)
1068 return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
1072 * Allows a registration based on a hash
1074 * @param string $hash
1076 * @return bool True, if the allow was successful
1078 * @throws HTTPException\InternalServerErrorException
1081 public static function allow(string $hash)
1083 $register = Register::getByHash($hash);
1084 if (!DBA::isResult($register)) {
1088 $user = User::getById($register['uid']);
1089 if (!DBA::isResult($user)) {
1093 Register::deleteByHash($hash);
1095 DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]);
1097 $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]);
1099 if (DBA::isResult($profile) && $profile['net-publish'] && DI::config()->get('system', 'directory')) {
1100 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
1101 Worker::add(PRIORITY_LOW, "Directory", $url);
1104 $l10n = DI::l10n()->withLang($register['language']);
1106 return User::sendRegisterOpenEmail(
1109 DI::config()->get('config', 'sitename'),
1110 DI::baseUrl()->get(),
1111 ($register['password'] ?? '') ?: 'Sent in a previous email'
1116 * Denys a pending registration
1118 * @param string $hash The hash of the pending user
1120 * This does not have to go through user_remove() and save the nickname
1121 * permanently against re-registration, as the person was not yet
1122 * allowed to have friends on this system
1124 * @return bool True, if the deny was successfull
1127 public static function deny(string $hash)
1129 $register = Register::getByHash($hash);
1130 if (!DBA::isResult($register)) {
1134 $user = User::getById($register['uid']);
1135 if (!DBA::isResult($user)) {
1139 return DBA::delete('user', ['uid' => $register['uid']]) &&
1140 Register::deleteByHash($register['hash']);
1144 * Creates a new user based on a minimal set and sends an email to this user
1146 * @param string $name The user's name
1147 * @param string $email The user's email address
1148 * @param string $nick The user's nick name
1149 * @param string $lang The user's language (default is english)
1151 * @return bool True, if the user was created successfully
1152 * @throws HTTPException\InternalServerErrorException
1153 * @throws ErrorException
1154 * @throws ImagickException
1156 public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT)
1161 throw new HTTPException\InternalServerErrorException('Invalid arguments.');
1164 $result = self::create([
1165 'username' => $name,
1167 'nickname' => $nick,
1172 $user = $result['user'];
1173 $preamble = Strings::deindent(DI::l10n()->t('
1175 the administrator of %2$s has set up an account for you.'));
1176 $body = Strings::deindent(DI::l10n()->t('
1177 The login details are as follows:
1183 You may change your password from your account "Settings" page after logging
1186 Please take a few moments to review the other account settings on that page.
1188 You may also wish to add some basic information to your default profile
1189 (on the "Profiles" page) so that other people can easily find you.
1191 We recommend setting your full name, adding a profile photo,
1192 adding some profile "keywords" (very useful in making new friends) - and
1193 perhaps what country you live in; if you do not wish to be more specific
1196 We fully respect your right to privacy, and none of these items are necessary.
1197 If you are new and do not know anybody here, they may help
1198 you to make some new and interesting friends.
1200 If you ever want to delete your account, you can do so at %1$s/removeme
1202 Thank you and welcome to %4$s.'));
1204 $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename'));
1205 $body = sprintf($body, DI::baseUrl()->get(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename'));
1207 $email = DI::emailer()
1209 ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body)
1211 ->withRecipient($user['email'])
1213 return DI::emailer()->send($email);
1217 * Sends pending registration confirmation email
1219 * @param array $user User record array
1220 * @param string $sitename
1221 * @param string $siteurl
1222 * @param string $password Plaintext password
1223 * @return NULL|boolean from notification() and email() inherited
1224 * @throws HTTPException\InternalServerErrorException
1226 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
1228 $body = Strings::deindent(DI::l10n()->t(
1231 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
1233 Your login details are as follows:
1246 $email = DI::emailer()
1248 ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
1250 ->withRecipient($user['email'])
1252 return DI::emailer()->send($email);
1256 * Sends registration confirmation
1258 * It's here as a function because the mail is sent from different parts
1260 * @param L10n $l10n The used language
1261 * @param array $user User record array
1262 * @param string $sitename
1263 * @param string $siteurl
1264 * @param string $password Plaintext password
1266 * @return NULL|boolean from notification() and email() inherited
1267 * @throws HTTPException\InternalServerErrorException
1269 public static function sendRegisterOpenEmail(L10n $l10n, $user, $sitename, $siteurl, $password)
1271 $preamble = Strings::deindent($l10n->t(
1274 Thank you for registering at %2$s. Your account has been created.
1279 $body = Strings::deindent($l10n->t(
1281 The login details are as follows:
1287 You may change your password from your account "Settings" page after logging
1290 Please take a few moments to review the other account settings on that page.
1292 You may also wish to add some basic information to your default profile
1293 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1295 We recommend setting your full name, adding a profile photo,
1296 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
1297 perhaps what country you live in; if you do not wish to be more specific
1300 We fully respect your right to privacy, and none of these items are necessary.
1301 If you are new and do not know anybody here, they may help
1302 you to make some new and interesting friends.
1304 If you ever want to delete your account, you can do so at %3$s/removeme
1306 Thank you and welcome to %2$s.',
1314 $email = DI::emailer()
1316 ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1318 ->withRecipient($user['email'])
1320 return DI::emailer()->send($email);
1324 * @param int $uid user to remove
1326 * @throws HTTPException\InternalServerErrorException
1328 public static function remove(int $uid)
1334 Logger::log('Removing user: ' . $uid);
1336 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1338 Hook::callAll('remove_user', $user);
1340 // save username (actually the nickname as it is guaranteed
1341 // unique), so it cannot be re-registered in the future.
1342 DBA::insert('userd', ['username' => $user['nickname']]);
1344 // The user and related data will be deleted in Friendica\Worker\ExpireAndRemoveUsers
1345 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1346 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1348 // Send an update to the directory
1349 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1350 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
1352 // Remove the user relevant data
1353 Worker::add(PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1359 * Return all identities to a user
1361 * @param int $uid The user id
1362 * @return array All identities for this user
1364 * Example for a return:
1368 * 'username' => 'maxmuster',
1369 * 'nickname' => 'Max Mustermann'
1373 * 'username' => 'johndoe',
1374 * 'nickname' => 'John Doe'
1379 public static function identities($uid)
1383 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1384 if (!DBA::isResult($user)) {
1388 if ($user['parent-uid'] == 0) {
1389 // First add our own entry
1391 'uid' => $user['uid'],
1392 'username' => $user['username'],
1393 'nickname' => $user['nickname']
1396 // Then add all the children
1399 ['uid', 'username', 'nickname'],
1400 ['parent-uid' => $user['uid'], 'account_removed' => false]
1402 if (DBA::isResult($r)) {
1403 $identities = array_merge($identities, DBA::toArray($r));
1406 // First entry is our parent
1409 ['uid', 'username', 'nickname'],
1410 ['uid' => $user['parent-uid'], 'account_removed' => false]
1412 if (DBA::isResult($r)) {
1413 $identities = DBA::toArray($r);
1416 // Then add all siblings
1419 ['uid', 'username', 'nickname'],
1420 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1422 if (DBA::isResult($r)) {
1423 $identities = array_merge($identities, DBA::toArray($r));
1428 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1430 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1431 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1434 if (DBA::isResult($r)) {
1435 $identities = array_merge($identities, DBA::toArray($r));
1442 * Returns statistical information about the current users of this node
1448 public static function getStatistics()
1452 'active_users_halfyear' => 0,
1453 'active_users_monthly' => 0,
1454 'active_users_weekly' => 0,
1457 $userStmt = DBA::select('owner-view', ['uid', 'login_date', 'last-item'],
1458 ["`verified` AND `login_date` > ? AND NOT `blocked`
1459 AND NOT `account_removed` AND NOT `account_expired`",
1460 DBA::NULL_DATETIME]);
1461 if (!DBA::isResult($userStmt)) {
1465 $halfyear = time() - (180 * 24 * 60 * 60);
1466 $month = time() - (30 * 24 * 60 * 60);
1467 $week = time() - (7 * 24 * 60 * 60);
1469 while ($user = DBA::fetch($userStmt)) {
1470 $statistics['total_users']++;
1472 if ((strtotime($user['login_date']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1474 $statistics['active_users_halfyear']++;
1477 if ((strtotime($user['login_date']) > $month) || (strtotime($user['last-item']) > $month)
1479 $statistics['active_users_monthly']++;
1482 if ((strtotime($user['login_date']) > $week) || (strtotime($user['last-item']) > $week)
1484 $statistics['active_users_weekly']++;
1487 DBA::close($userStmt);
1493 * Get all users of the current node
1495 * @param int $start Start count (Default is 0)
1496 * @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE)
1497 * @param string $type The type of users, which should get (all, bocked, removed)
1498 * @param string $order Order of the user list (Default is 'contact.name')
1499 * @param bool $descending Order direction (Default is ascending)
1501 * @return array The list of the users
1504 public static function getList($start = 0, $count = Pager::ITEMS_PER_PAGE, $type = 'all', $order = 'name', bool $descending = false)
1506 $param = ['limit' => [$start, $count], 'order' => [$order => $descending]];
1510 $condition['account_removed'] = false;
1511 $condition['blocked'] = false;
1514 $condition['blocked'] = true;
1517 $condition['account_removed'] = true;
1521 return DBA::selectToArray('owner-view', [], $condition, $param);