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\PasswordExposed;
26 use Friendica\Content\Pager;
27 use Friendica\Core\Hook;
28 use Friendica\Core\L10n;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Model\TwoFactor\AppSpecificPassword;
36 use Friendica\Network\HTTPException\InternalServerErrorException;
37 use Friendica\Object\Image;
38 use Friendica\Util\Crypto;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Images;
41 use Friendica\Util\Network;
42 use Friendica\Util\Strings;
43 use Friendica\Worker\Delivery;
47 * This class handles User related functions
54 * PAGE_FLAGS_NORMAL is a typical personal profile account
55 * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
56 * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
57 * write access to wall and comments (no email and not included in page owner's ACL lists)
58 * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
62 const PAGE_FLAGS_NORMAL = 0;
63 const PAGE_FLAGS_SOAPBOX = 1;
64 const PAGE_FLAGS_COMMUNITY = 2;
65 const PAGE_FLAGS_FREELOVE = 3;
66 const PAGE_FLAGS_BLOG = 4;
67 const PAGE_FLAGS_PRVGROUP = 5;
75 * ACCOUNT_TYPE_PERSON - the account belongs to a person
76 * Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
78 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
79 * Associated page type: PAGE_FLAGS_SOAPBOX
81 * ACCOUNT_TYPE_NEWS - the account is a news reflector
82 * Associated page type: PAGE_FLAGS_SOAPBOX
84 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
85 * Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
87 * ACCOUNT_TYPE_RELAY - the account is a relay
88 * This will only be assigned to contacts, not to user accounts
91 const ACCOUNT_TYPE_PERSON = 0;
92 const ACCOUNT_TYPE_ORGANISATION = 1;
93 const ACCOUNT_TYPE_NEWS = 2;
94 const ACCOUNT_TYPE_COMMUNITY = 3;
95 const ACCOUNT_TYPE_RELAY = 4;
100 private static $owner;
103 * Fetch the system account
105 * @return array system account
107 public static function getSystemAccount()
109 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
110 if (!DBA::isResult($system)) {
111 self::createSystemAccount();
112 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
113 if (!DBA::isResult($system)) {
118 $system['spubkey'] = $system['uprvkey'] = $system['prvkey'];
119 $system['username'] = $system['name'];
120 $system['nickname'] = $system['nick'];
125 * Create the system account
129 private static function createSystemAccount()
131 $system_actor_name = self::getActorName();
132 if (empty($system_actor_name)) {
136 $keys = Crypto::newKeypair(4096);
137 if ($keys === false) {
138 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
143 $system['created'] = DateTimeFormat::utcNow();
144 $system['self'] = true;
145 $system['network'] = Protocol::ACTIVITYPUB;
146 $system['name'] = 'System Account';
147 $system['addr'] = $system_actor_name . '@' . DI::baseUrl()->getHostname();
148 $system['nick'] = $system_actor_name;
149 $system['avatar'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
150 $system['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
151 $system['thumb'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_THUMB;
152 $system['micro'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_MICRO;
153 $system['url'] = DI::baseUrl() . '/friendica';
154 $system['nurl'] = Strings::normaliseLink($system['url']);
155 $system['pubkey'] = $keys['pubkey'];
156 $system['prvkey'] = $keys['prvkey'];
157 $system['blocked'] = 0;
158 $system['pending'] = 0;
159 $system['contact-type'] = Contact::TYPE_RELAY; // In AP this is translated to 'Application'
160 $system['name-date'] = DateTimeFormat::utcNow();
161 $system['uri-date'] = DateTimeFormat::utcNow();
162 $system['avatar-date'] = DateTimeFormat::utcNow();
163 $system['closeness'] = 0;
164 $system['baseurl'] = DI::baseUrl();
165 $system['gsid'] = GServer::getID($system['baseurl']);
166 DBA::insert('contact', $system);
170 * Detect a usable actor name
172 * @return string actor account name
174 public static function getActorName()
176 $system_actor_name = DI::config()->get('system', 'actor_name');
177 if (!empty($system_actor_name)) {
178 $self = Contact::selectFirst(['nick'], ['uid' => 0, 'self' => true]);
179 if (!empty($self['nick'])) {
180 if ($self['nick'] != $system_actor_name) {
181 // Reset the actor name to the already used name
182 DI::config()->set('system', 'actor_name', $self['nick']);
183 $system_actor_name = $self['nick'];
186 return $system_actor_name;
189 // List of possible actor names
190 $possible_accounts = ['friendica', 'actor', 'system', 'internal'];
191 foreach ($possible_accounts as $name) {
192 if (!DBA::exists('user', ['nickname' => $name, 'account_removed' => false, 'expire']) &&
193 !DBA::exists('userd', ['username' => $name])) {
194 DI::config()->set('system', 'actor_name', $name);
202 * Returns true if a user record exists with the provided id
204 * @param integer $uid
208 public static function exists($uid)
210 return DBA::exists('user', ['uid' => $uid]);
214 * @param integer $uid
215 * @param array $fields
216 * @return array|boolean User record if it exists, false otherwise
219 public static function getById($uid, array $fields = [])
221 return DBA::selectFirst('user', $fields, ['uid' => $uid]);
225 * Returns a user record based on it's GUID
227 * @param string $guid The guid of the user
228 * @param array $fields The fields to retrieve
229 * @param bool $active True, if only active records are searched
231 * @return array|boolean User record if it exists, false otherwise
234 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
237 $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
239 $cond = ['guid' => $guid];
242 return DBA::selectFirst('user', $fields, $cond);
246 * @param string $nickname
247 * @param array $fields
248 * @return array|boolean User record if it exists, false otherwise
251 public static function getByNickname($nickname, array $fields = [])
253 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
257 * Returns the user id of a given profile URL
261 * @return integer user id
264 public static function getIdForURL(string $url)
266 // Avoid any database requests when the hostname isn't even part of the url.
267 if (!strpos($url, DI::baseUrl()->getHostname())) {
271 $self = Contact::selectFirst(['uid'], ['self' => true, 'nurl' => Strings::normaliseLink($url)]);
272 if (!empty($self['uid'])) {
276 $self = Contact::selectFirst(['uid'], ['self' => true, 'addr' => $url]);
277 if (!empty($self['uid'])) {
281 $self = Contact::selectFirst(['uid'], ['self' => true, 'alias' => [$url, Strings::normaliseLink($url)]]);
282 if (!empty($self['uid'])) {
290 * Get a user based on its email
292 * @param string $email
293 * @param array $fields
295 * @return array|boolean User record if it exists, false otherwise
299 public static function getByEmail($email, array $fields = [])
301 return DBA::selectFirst('user', $fields, ['email' => $email]);
305 * Fetch the user array of the administrator. The first one if there are several.
307 * @param array $fields
310 public static function getFirstAdmin(array $fields = [])
312 if (!empty(DI::config()->get('config', 'admin_nickname'))) {
313 return self::getByNickname(DI::config()->get('config', 'admin_nickname'), $fields);
314 } elseif (!empty(DI::config()->get('config', 'admin_email'))) {
315 $adminList = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
316 return self::getByEmail($adminList[0], $fields);
323 * Get owner data by user id
326 * @param boolean $check_valid Test if data is invalid and correct it
327 * @return boolean|array
330 public static function getOwnerDataById(int $uid, bool $check_valid = true)
332 if (!empty(self::$owner[$uid])) {
333 return self::$owner[$uid];
336 $owner = DBA::selectFirst('owner-view', [], ['uid' => $uid]);
337 if (!DBA::isResult($owner)) {
338 if (!DBA::exists('user', ['uid' => $uid]) || !$check_valid) {
341 Contact::createSelfFromUserId($uid);
342 $owner = self::getOwnerDataById($uid, false);
345 if (empty($owner['nickname'])) {
353 // Check if the returned data is valid, otherwise fix it. See issue #6122
355 // Check for correct url and normalised nurl
356 $url = DI::baseUrl() . '/profile/' . $owner['nickname'];
357 $repair = ($owner['url'] != $url) || ($owner['nurl'] != Strings::normaliseLink($owner['url']));
360 // Check if "addr" is present and correct
361 $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
362 $repair = ($addr != $owner['addr']);
366 // Check if the avatar field is filled and the photo directs to the correct path
367 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
368 if (DBA::isResult($avatar)) {
369 $repair = empty($owner['avatar']) || !strpos($owner['photo'], $avatar['resource-id']);
374 Contact::updateSelfFromUserID($uid);
375 // Return the corrected data and avoid a loop
376 $owner = self::getOwnerDataById($uid, false);
379 self::$owner[$uid] = $owner;
384 * Get owner data by nick name
387 * @return boolean|array
390 public static function getOwnerDataByNick($nick)
392 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
394 if (!DBA::isResult($user)) {
398 return self::getOwnerDataById($user['uid']);
402 * Returns the default group for a given user and network
404 * @param int $uid User id
405 * @param string $network network name
407 * @return int group id
408 * @throws InternalServerErrorException
410 public static function getDefaultGroup($uid, $network = '')
414 if ($network == Protocol::OSTATUS) {
415 $default_group = DI::pConfig()->get($uid, "ostatus", "default_group");
418 if ($default_group != 0) {
419 return $default_group;
422 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
424 if (DBA::isResult($user)) {
425 $default_group = $user["def_gid"];
428 return $default_group;
433 * Authenticate a user with a clear text password
435 * @param mixed $user_info
436 * @param string $password
437 * @param bool $third_party
438 * @return int|boolean
439 * @deprecated since version 3.6
440 * @see User::getIdFromPasswordAuthentication()
442 public static function authenticate($user_info, $password, $third_party = false)
445 return self::getIdFromPasswordAuthentication($user_info, $password, $third_party);
446 } catch (Exception $ex) {
452 * Authenticate a user with a clear text password
454 * Returns the user id associated with a successful password authentication
456 * @param mixed $user_info
457 * @param string $password
458 * @param bool $third_party
459 * @return int User Id if authentication is successful
462 public static function getIdFromPasswordAuthentication($user_info, $password, $third_party = false)
464 $user = self::getAuthenticationInfo($user_info);
466 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
467 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
468 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
471 } elseif (strpos($user['password'], '$') === false) {
472 //Legacy hash that has not been replaced by a new hash yet
473 if (self::hashPasswordLegacy($password) === $user['password']) {
474 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
478 } elseif (!empty($user['legacy_password'])) {
479 //Legacy hash that has been double-hashed and not replaced by a new hash yet
480 //Warning: `legacy_password` is not necessary in sync with the content of `password`
481 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
482 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
486 } elseif (password_verify($password, $user['password'])) {
488 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
489 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
495 throw new Exception(DI::l10n()->t('Login failed'));
499 * Returns authentication info from various parameters types
501 * User info can be any of the following:
504 * - User email or username or nickname
505 * - User array with at least the uid and the hashed password
507 * @param mixed $user_info
511 private static function getAuthenticationInfo($user_info)
515 if (is_object($user_info) || is_array($user_info)) {
516 if (is_object($user_info)) {
517 $user = (array) $user_info;
524 || !isset($user['password'])
525 || !isset($user['legacy_password'])
527 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
529 } elseif (is_int($user_info) || is_string($user_info)) {
530 if (is_int($user_info)) {
531 $user = DBA::selectFirst(
533 ['uid', 'password', 'legacy_password'],
537 'account_expired' => 0,
538 'account_removed' => 0,
543 $fields = ['uid', 'password', 'legacy_password'];
545 "(`email` = ? OR `username` = ? OR `nickname` = ?)
546 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
547 $user_info, $user_info, $user_info
549 $user = DBA::selectFirst('user', $fields, $condition);
552 if (!DBA::isResult($user)) {
553 throw new Exception(DI::l10n()->t('User not found'));
561 * Generates a human-readable random password
565 public static function generateNewPassword()
567 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
571 * Checks if the provided plaintext password has been exposed or not
573 * @param string $password
577 public static function isPasswordExposed($password)
579 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
580 $cache->changeConfig([
581 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
585 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
587 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
588 } catch (\Exception $e) {
589 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
590 'code' => $e->getCode(),
591 'file' => $e->getFile(),
592 'line' => $e->getLine(),
593 'trace' => $e->getTraceAsString()
601 * Legacy hashing function, kept for password migration purposes
603 * @param string $password
606 private static function hashPasswordLegacy($password)
608 return hash('whirlpool', $password);
612 * Global user password hashing function
614 * @param string $password
618 public static function hashPassword($password)
620 if (!trim($password)) {
621 throw new Exception(DI::l10n()->t('Password can\'t be empty'));
624 return password_hash($password, PASSWORD_DEFAULT);
628 * Updates a user row with a new plaintext password
631 * @param string $password
635 public static function updatePassword($uid, $password)
637 $password = trim($password);
639 if (empty($password)) {
640 throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
643 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
644 throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
647 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
649 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
650 throw new Exception(DI::l10n()->t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
653 return self::updatePasswordHashed($uid, self::hashPassword($password));
657 * Updates a user row with a new hashed password.
658 * Empties the password reset token field just in case.
661 * @param string $pasword_hashed
665 private static function updatePasswordHashed($uid, $pasword_hashed)
668 'password' => $pasword_hashed,
670 'pwdreset_time' => null,
671 'legacy_password' => false
673 return DBA::update('user', $fields, ['uid' => $uid]);
677 * Checks if a nickname is in the list of the forbidden nicknames
679 * Check if a nickname is forbidden from registration on the node by the
680 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
683 * @param string $nickname The nickname that should be checked
684 * @return boolean True is the nickname is blocked on the node
685 * @throws InternalServerErrorException
687 public static function isNicknameBlocked($nickname)
689 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
690 if (!empty($forbidden_nicknames)) {
691 $forbidden = explode(',', $forbidden_nicknames);
692 $forbidden = array_map('trim', $forbidden);
697 // Add the name of the internal actor to the "forbidden" list
698 $actor_name = self::getActorName();
699 if (!empty($actor_name)) {
700 $forbidden[] = $actor_name;
703 if (empty($forbidden)) {
707 // check if the nickname is in the list of blocked nicknames
708 if (in_array(strtolower($nickname), $forbidden)) {
717 * Catch-all user creation function
719 * Creates a user from the provided data array, either form fields or OpenID.
720 * Required: { username, nickname, email } or { openid_url }
722 * Performs the following:
723 * - Sends to the OpenId auth URL (if relevant)
724 * - Creates new key pairs for crypto
725 * - Create self-contact
726 * - Create profile image
730 * @throws \ErrorException
731 * @throws InternalServerErrorException
732 * @throws \ImagickException
735 public static function create(array $data)
737 $return = ['user' => null, 'password' => ''];
739 $using_invites = DI::config()->get('system', 'invitation_only');
741 $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
742 $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
743 $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
744 $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
745 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
746 $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
747 $password = !empty($data['password']) ? trim($data['password']) : '';
748 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
749 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
750 $blocked = !empty($data['blocked']);
751 $verified = !empty($data['verified']);
752 $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
754 $netpublish = $publish = !empty($data['profile_publish_reg']);
756 if ($password1 != $confirm) {
757 throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
758 } elseif ($password1 != '') {
759 $password = $password1;
762 if ($using_invites) {
764 throw new Exception(DI::l10n()->t('An invitation is required.'));
767 if (!Register::existsByHash($invite_id)) {
768 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
772 /// @todo Check if this part is really needed. We should have fetched all this data in advance
773 if (empty($username) || empty($email) || empty($nickname)) {
775 if (!Network::isUrlValid($openid_url)) {
776 throw new Exception(DI::l10n()->t('Invalid OpenID url'));
778 $_SESSION['register'] = 1;
779 $_SESSION['openid'] = $openid_url;
781 $openid = new LightOpenID(DI::baseUrl()->getHostname());
782 $openid->identity = $openid_url;
783 $openid->returnUrl = DI::baseUrl() . '/openid';
784 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
785 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
787 $authurl = $openid->authUrl();
788 } catch (Exception $e) {
789 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);
791 System::externalRedirect($authurl);
795 throw new Exception(DI::l10n()->t('Please enter the required information.'));
798 if (!Network::isUrlValid($openid_url)) {
802 // collapse multiple spaces in name
803 $username = preg_replace('/ +/', ' ', $username);
805 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
806 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
808 if ($username_min_length > $username_max_length) {
809 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);
810 $tmp = $username_min_length;
811 $username_min_length = $username_max_length;
812 $username_max_length = $tmp;
815 if (mb_strlen($username) < $username_min_length) {
816 throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
819 if (mb_strlen($username) > $username_max_length) {
820 throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
823 // So now we are just looking for a space in the full name.
824 $loose_reg = DI::config()->get('system', 'no_regfullname');
826 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
827 if (strpos($username, ' ') === false) {
828 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
832 if (!Network::isEmailDomainAllowed($email)) {
833 throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
836 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
837 throw new Exception(DI::l10n()->t('Not a valid email address.'));
839 if (self::isNicknameBlocked($nickname)) {
840 throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
843 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
844 throw new Exception(DI::l10n()->t('Cannot use that email.'));
847 // Disallow somebody creating an account using openid that uses the admin email address,
848 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
849 if (DI::config()->get('config', 'admin_email') && strlen($openid_url)) {
850 $adminlist = explode(',', str_replace(' ', '', strtolower(DI::config()->get('config', 'admin_email'))));
851 if (in_array(strtolower($email), $adminlist)) {
852 throw new Exception(DI::l10n()->t('Cannot use that email.'));
856 $nickname = $data['nickname'] = strtolower($nickname);
858 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
859 throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
862 // Check existing and deleted accounts for this nickname.
864 DBA::exists('user', ['nickname' => $nickname])
865 || DBA::exists('userd', ['username' => $nickname])
867 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
870 $new_password = strlen($password) ? $password : User::generateNewPassword();
871 $new_password_encoded = self::hashPassword($new_password);
873 $return['password'] = $new_password;
875 $keys = Crypto::newKeypair(4096);
876 if ($keys === false) {
877 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
880 $prvkey = $keys['prvkey'];
881 $pubkey = $keys['pubkey'];
883 // Create another keypair for signing/verifying salmon protocol messages.
884 $sres = Crypto::newKeypair(512);
885 $sprvkey = $sres['prvkey'];
886 $spubkey = $sres['pubkey'];
888 $insert_result = DBA::insert('user', [
889 'guid' => System::createUUID(),
890 'username' => $username,
891 'password' => $new_password_encoded,
893 'openid' => $openid_url,
894 'nickname' => $nickname,
897 'spubkey' => $spubkey,
898 'sprvkey' => $sprvkey,
899 'verified' => $verified,
900 'blocked' => $blocked,
901 'language' => $language,
903 'register_date' => DateTimeFormat::utcNow(),
904 'default-location' => ''
907 if ($insert_result) {
908 $uid = DBA::lastInsertId();
909 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
911 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
915 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
918 // if somebody clicked submit twice very quickly, they could end up with two accounts
919 // due to race condition. Remove this one.
920 $user_count = DBA::count('user', ['nickname' => $nickname]);
921 if ($user_count > 1) {
922 DBA::delete('user', ['uid' => $uid]);
924 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
927 $insert_result = DBA::insert('profile', [
930 'photo' => DI::baseUrl() . "/photo/profile/{$uid}.jpg",
931 'thumb' => DI::baseUrl() . "/photo/avatar/{$uid}.jpg",
932 'publish' => $publish,
933 'net-publish' => $netpublish,
935 if (!$insert_result) {
936 DBA::delete('user', ['uid' => $uid]);
938 throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
941 // Create the self contact
942 if (!Contact::createSelfFromUserId($uid)) {
943 DBA::delete('user', ['uid' => $uid]);
945 throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
948 // Create a group with no members. This allows somebody to use it
949 // right away as a default group for new contacts.
950 $def_gid = Group::create($uid, DI::l10n()->t('Friends'));
952 DBA::delete('user', ['uid' => $uid]);
954 throw new Exception(DI::l10n()->t('An error occurred creating your default contact group. Please try again.'));
957 $fields = ['def_gid' => $def_gid];
958 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
959 $fields['allow_gid'] = '<' . $def_gid . '>';
962 DBA::update('user', $fields, ['uid' => $uid]);
964 // if we have no OpenID photo try to look up an avatar
965 if (!strlen($photo)) {
966 $photo = Network::lookupAvatarByEmail($email);
969 // unless there is no avatar-addon loaded
970 if (strlen($photo)) {
971 $photo_failure = false;
973 $filename = basename($photo);
974 $curlResult = DI::httpRequest()->get($photo, true);
975 if ($curlResult->isSuccess()) {
976 $img_str = $curlResult->getBody();
977 $type = $curlResult->getContentType();
983 $type = Images::getMimeTypeByData($img_str, $photo, $type);
985 $Image = new Image($img_str, $type);
986 if ($Image->isValid()) {
987 $Image->scaleToSquare(300);
989 $resource_id = Photo::newResource();
991 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 4);
994 $photo_failure = true;
997 $Image->scaleDown(80);
999 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 5);
1002 $photo_failure = true;
1005 $Image->scaleDown(48);
1007 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 6);
1010 $photo_failure = true;
1013 if (!$photo_failure) {
1014 Photo::update(['profile' => 1], ['resource-id' => $resource_id]);
1019 Hook::callAll('register_account', $uid);
1021 $return['user'] = $user;
1026 * Sets block state for a given user
1028 * @param int $uid The user id
1029 * @param bool $block Block state (default is true)
1031 * @return bool True, if successfully blocked
1035 public static function block(int $uid, bool $block = true)
1037 return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
1041 * Allows a registration based on a hash
1043 * @param string $hash
1045 * @return bool True, if the allow was successful
1047 * @throws InternalServerErrorException
1050 public static function allow(string $hash)
1052 $register = Register::getByHash($hash);
1053 if (!DBA::isResult($register)) {
1057 $user = User::getById($register['uid']);
1058 if (!DBA::isResult($user)) {
1062 Register::deleteByHash($hash);
1064 DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]);
1066 $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]);
1068 if (DBA::isResult($profile) && $profile['net-publish'] && DI::config()->get('system', 'directory')) {
1069 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
1070 Worker::add(PRIORITY_LOW, "Directory", $url);
1073 $l10n = DI::l10n()->withLang($register['language']);
1075 return User::sendRegisterOpenEmail(
1078 DI::config()->get('config', 'sitename'),
1079 DI::baseUrl()->get(),
1080 ($register['password'] ?? '') ?: 'Sent in a previous email'
1085 * Denys a pending registration
1087 * @param string $hash The hash of the pending user
1089 * This does not have to go through user_remove() and save the nickname
1090 * permanently against re-registration, as the person was not yet
1091 * allowed to have friends on this system
1093 * @return bool True, if the deny was successfull
1096 public static function deny(string $hash)
1098 $register = Register::getByHash($hash);
1099 if (!DBA::isResult($register)) {
1103 $user = User::getById($register['uid']);
1104 if (!DBA::isResult($user)) {
1108 return DBA::delete('user', ['uid' => $register['uid']]) &&
1109 Register::deleteByHash($register['hash']);
1113 * Creates a new user based on a minimal set and sends an email to this user
1115 * @param string $name The user's name
1116 * @param string $email The user's email address
1117 * @param string $nick The user's nick name
1118 * @param string $lang The user's language (default is english)
1120 * @return bool True, if the user was created successfully
1121 * @throws InternalServerErrorException
1122 * @throws \ErrorException
1123 * @throws \ImagickException
1125 public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT)
1130 throw new InternalServerErrorException('Invalid arguments.');
1133 $result = self::create([
1134 'username' => $name,
1136 'nickname' => $nick,
1141 $user = $result['user'];
1142 $preamble = Strings::deindent(DI::l10n()->t('
1144 the administrator of %2$s has set up an account for you.'));
1145 $body = Strings::deindent(DI::l10n()->t('
1146 The login details are as follows:
1152 You may change your password from your account "Settings" page after logging
1155 Please take a few moments to review the other account settings on that page.
1157 You may also wish to add some basic information to your default profile
1158 (on the "Profiles" page) so that other people can easily find you.
1160 We recommend setting your full name, adding a profile photo,
1161 adding some profile "keywords" (very useful in making new friends) - and
1162 perhaps what country you live in; if you do not wish to be more specific
1165 We fully respect your right to privacy, and none of these items are necessary.
1166 If you are new and do not know anybody here, they may help
1167 you to make some new and interesting friends.
1169 If you ever want to delete your account, you can do so at %1$s/removeme
1171 Thank you and welcome to %4$s.'));
1173 $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename'));
1174 $body = sprintf($body, DI::baseUrl()->get(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename'));
1176 $email = DI::emailer()
1178 ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body)
1180 ->withRecipient($user['email'])
1182 return DI::emailer()->send($email);
1186 * Sends pending registration confirmation email
1188 * @param array $user User record array
1189 * @param string $sitename
1190 * @param string $siteurl
1191 * @param string $password Plaintext password
1192 * @return NULL|boolean from notification() and email() inherited
1193 * @throws InternalServerErrorException
1195 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
1197 $body = Strings::deindent(DI::l10n()->t(
1200 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
1202 Your login details are as follows:
1215 $email = DI::emailer()
1217 ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
1219 ->withRecipient($user['email'])
1221 return DI::emailer()->send($email);
1225 * Sends registration confirmation
1227 * It's here as a function because the mail is sent from different parts
1229 * @param \Friendica\Core\L10n $l10n The used language
1230 * @param array $user User record array
1231 * @param string $sitename
1232 * @param string $siteurl
1233 * @param string $password Plaintext password
1235 * @return NULL|boolean from notification() and email() inherited
1236 * @throws InternalServerErrorException
1238 public static function sendRegisterOpenEmail(\Friendica\Core\L10n $l10n, $user, $sitename, $siteurl, $password)
1240 $preamble = Strings::deindent($l10n->t(
1243 Thank you for registering at %2$s. Your account has been created.
1248 $body = Strings::deindent($l10n->t(
1250 The login details are as follows:
1256 You may change your password from your account "Settings" page after logging
1259 Please take a few moments to review the other account settings on that page.
1261 You may also wish to add some basic information to your default profile
1262 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1264 We recommend setting your full name, adding a profile photo,
1265 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
1266 perhaps what country you live in; if you do not wish to be more specific
1269 We fully respect your right to privacy, and none of these items are necessary.
1270 If you are new and do not know anybody here, they may help
1271 you to make some new and interesting friends.
1273 If you ever want to delete your account, you can do so at %3$s/removeme
1275 Thank you and welcome to %2$s.',
1283 $email = DI::emailer()
1285 ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1287 ->withRecipient($user['email'])
1289 return DI::emailer()->send($email);
1293 * @param int $uid user to remove
1295 * @throws InternalServerErrorException
1297 public static function remove(int $uid)
1303 Logger::log('Removing user: ' . $uid);
1305 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1307 Hook::callAll('remove_user', $user);
1309 // save username (actually the nickname as it is guaranteed
1310 // unique), so it cannot be re-registered in the future.
1311 DBA::insert('userd', ['username' => $user['nickname']]);
1313 // The user and related data will be deleted in Friendica\Worker\ExpireAndRemoveUsers
1314 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1315 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1317 // Send an update to the directory
1318 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1319 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
1321 // Remove the user relevant data
1322 Worker::add(PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1328 * Return all identities to a user
1330 * @param int $uid The user id
1331 * @return array All identities for this user
1333 * Example for a return:
1337 * 'username' => 'maxmuster',
1338 * 'nickname' => 'Max Mustermann'
1342 * 'username' => 'johndoe',
1343 * 'nickname' => 'John Doe'
1348 public static function identities($uid)
1352 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1353 if (!DBA::isResult($user)) {
1357 if ($user['parent-uid'] == 0) {
1358 // First add our own entry
1360 'uid' => $user['uid'],
1361 'username' => $user['username'],
1362 'nickname' => $user['nickname']
1365 // Then add all the children
1368 ['uid', 'username', 'nickname'],
1369 ['parent-uid' => $user['uid'], 'account_removed' => false]
1371 if (DBA::isResult($r)) {
1372 $identities = array_merge($identities, DBA::toArray($r));
1375 // First entry is our parent
1378 ['uid', 'username', 'nickname'],
1379 ['uid' => $user['parent-uid'], 'account_removed' => false]
1381 if (DBA::isResult($r)) {
1382 $identities = DBA::toArray($r);
1385 // Then add all siblings
1388 ['uid', 'username', 'nickname'],
1389 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1391 if (DBA::isResult($r)) {
1392 $identities = array_merge($identities, DBA::toArray($r));
1397 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1399 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1400 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1403 if (DBA::isResult($r)) {
1404 $identities = array_merge($identities, DBA::toArray($r));
1411 * Returns statistical information about the current users of this node
1417 public static function getStatistics()
1421 'active_users_halfyear' => 0,
1422 'active_users_monthly' => 0,
1423 'active_users_weekly' => 0,
1426 $userStmt = DBA::select('owner-view', ['uid', 'login_date', 'last-item'],
1427 ["`verified` AND `login_date` > ? AND NOT `blocked`
1428 AND NOT `account_removed` AND NOT `account_expired`",
1429 DBA::NULL_DATETIME]);
1430 if (!DBA::isResult($userStmt)) {
1434 $halfyear = time() - (180 * 24 * 60 * 60);
1435 $month = time() - (30 * 24 * 60 * 60);
1436 $week = time() - (7 * 24 * 60 * 60);
1438 while ($user = DBA::fetch($userStmt)) {
1439 $statistics['total_users']++;
1441 if ((strtotime($user['login_date']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1443 $statistics['active_users_halfyear']++;
1446 if ((strtotime($user['login_date']) > $month) || (strtotime($user['last-item']) > $month)
1448 $statistics['active_users_monthly']++;
1451 if ((strtotime($user['login_date']) > $week) || (strtotime($user['last-item']) > $week)
1453 $statistics['active_users_weekly']++;
1456 DBA::close($userStmt);
1462 * Get all users of the current node
1464 * @param int $start Start count (Default is 0)
1465 * @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE)
1466 * @param string $type The type of users, which should get (all, bocked, removed)
1467 * @param string $order Order of the user list (Default is 'contact.name')
1468 * @param bool $descending Order direction (Default is ascending)
1470 * @return array The list of the users
1473 public static function getList($start = 0, $count = Pager::ITEMS_PER_PAGE, $type = 'all', $order = 'name', bool $descending = false)
1475 $param = ['limit' => [$start, $count], 'order' => [$order => $descending]];
1479 $condition['account_removed'] = false;
1480 $condition['blocked'] = false;
1483 $condition['blocked'] = true;
1486 $condition['account_removed'] = true;
1490 return DBA::selectToArray('owner-view', [], $condition, $param);