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\Core\Hook;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\TwoFactor\AppSpecificPassword;
35 use Friendica\Network\HTTPException\InternalServerErrorException;
36 use Friendica\Object\Image;
37 use Friendica\Util\Crypto;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Images;
40 use Friendica\Util\Network;
41 use Friendica\Util\Strings;
42 use Friendica\Worker\Delivery;
46 * This class handles User related functions
53 * PAGE_FLAGS_NORMAL is a typical personal profile account
54 * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
55 * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
56 * write access to wall and comments (no email and not included in page owner's ACL lists)
57 * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
61 const PAGE_FLAGS_NORMAL = 0;
62 const PAGE_FLAGS_SOAPBOX = 1;
63 const PAGE_FLAGS_COMMUNITY = 2;
64 const PAGE_FLAGS_FREELOVE = 3;
65 const PAGE_FLAGS_BLOG = 4;
66 const PAGE_FLAGS_PRVGROUP = 5;
74 * ACCOUNT_TYPE_PERSON - the account belongs to a person
75 * Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
77 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
78 * Associated page type: PAGE_FLAGS_SOAPBOX
80 * ACCOUNT_TYPE_NEWS - the account is a news reflector
81 * Associated page type: PAGE_FLAGS_SOAPBOX
83 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
84 * Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
86 * ACCOUNT_TYPE_RELAY - the account is a relay
87 * This will only be assigned to contacts, not to user accounts
90 const ACCOUNT_TYPE_PERSON = 0;
91 const ACCOUNT_TYPE_ORGANISATION = 1;
92 const ACCOUNT_TYPE_NEWS = 2;
93 const ACCOUNT_TYPE_COMMUNITY = 3;
94 const ACCOUNT_TYPE_RELAY = 4;
100 * Returns true if a user record exists with the provided id
102 * @param integer $uid
106 public static function exists($uid)
108 return DBA::exists('user', ['uid' => $uid]);
112 * @param integer $uid
113 * @param array $fields
114 * @return array|boolean User record if it exists, false otherwise
117 public static function getById($uid, array $fields = [])
119 return DBA::selectFirst('user', $fields, ['uid' => $uid]);
123 * Returns a user record based on it's GUID
125 * @param string $guid The guid of the user
126 * @param array $fields The fields to retrieve
127 * @param bool $active True, if only active records are searched
129 * @return array|boolean User record if it exists, false otherwise
132 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
135 $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
137 $cond = ['guid' => $guid];
140 return DBA::selectFirst('user', $fields, $cond);
144 * @param string $nickname
145 * @param array $fields
146 * @return array|boolean User record if it exists, false otherwise
149 public static function getByNickname($nickname, array $fields = [])
151 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
155 * Returns the user id of a given profile URL
159 * @return integer user id
162 public static function getIdForURL($url)
164 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => Strings::normaliseLink($url), 'self' => true]);
165 if (!DBA::isResult($self)) {
173 * Get a user based on its email
175 * @param string $email
176 * @param array $fields
178 * @return array|boolean User record if it exists, false otherwise
182 public static function getByEmail($email, array $fields = [])
184 return DBA::selectFirst('user', $fields, ['email' => $email]);
188 * Get owner data by user id
191 * @param boolean $check_valid Test if data is invalid and correct it
192 * @return boolean|array
195 public static function getOwnerDataById($uid, $check_valid = true)
197 $r = DBA::fetchFirst(
200 `user`.`prvkey` AS `uprvkey`,
206 `user`.`account-type`,
208 `user`.`account_removed`,
212 ON `user`.`uid` = `contact`.`uid`
213 WHERE `contact`.`uid` = ?
218 if (!DBA::isResult($r)) {
222 if (empty($r['nickname'])) {
230 // Check if the returned data is valid, otherwise fix it. See issue #6122
232 // Check for correct url and normalised nurl
233 $url = DI::baseUrl() . '/profile/' . $r['nickname'];
234 $repair = ($r['url'] != $url) || ($r['nurl'] != Strings::normaliseLink($r['url']));
237 // Check if "addr" is present and correct
238 $addr = $r['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
239 $repair = ($addr != $r['addr']);
243 // Check if the avatar field is filled and the photo directs to the correct path
244 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
245 if (DBA::isResult($avatar)) {
246 $repair = empty($r['avatar']) || !strpos($r['photo'], $avatar['resource-id']);
251 Contact::updateSelfFromUserID($uid);
252 // Return the corrected data and avoid a loop
253 $r = self::getOwnerDataById($uid, false);
260 * Get owner data by nick name
263 * @return boolean|array
266 public static function getOwnerDataByNick($nick)
268 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
270 if (!DBA::isResult($user)) {
274 return self::getOwnerDataById($user['uid']);
278 * Returns the default group for a given user and network
280 * @param int $uid User id
281 * @param string $network network name
283 * @return int group id
284 * @throws InternalServerErrorException
286 public static function getDefaultGroup($uid, $network = '')
290 if ($network == Protocol::OSTATUS) {
291 $default_group = DI::pConfig()->get($uid, "ostatus", "default_group");
294 if ($default_group != 0) {
295 return $default_group;
298 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
300 if (DBA::isResult($user)) {
301 $default_group = $user["def_gid"];
304 return $default_group;
309 * Authenticate a user with a clear text password
311 * @param mixed $user_info
312 * @param string $password
313 * @param bool $third_party
314 * @return int|boolean
315 * @deprecated since version 3.6
316 * @see User::getIdFromPasswordAuthentication()
318 public static function authenticate($user_info, $password, $third_party = false)
321 return self::getIdFromPasswordAuthentication($user_info, $password, $third_party);
322 } catch (Exception $ex) {
328 * Authenticate a user with a clear text password
330 * Returns the user id associated with a successful password authentication
332 * @param mixed $user_info
333 * @param string $password
334 * @param bool $third_party
335 * @return int User Id if authentication is successful
338 public static function getIdFromPasswordAuthentication($user_info, $password, $third_party = false)
340 $user = self::getAuthenticationInfo($user_info);
342 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
343 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
344 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
347 } elseif (strpos($user['password'], '$') === false) {
348 //Legacy hash that has not been replaced by a new hash yet
349 if (self::hashPasswordLegacy($password) === $user['password']) {
350 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
354 } elseif (!empty($user['legacy_password'])) {
355 //Legacy hash that has been double-hashed and not replaced by a new hash yet
356 //Warning: `legacy_password` is not necessary in sync with the content of `password`
357 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
358 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
362 } elseif (password_verify($password, $user['password'])) {
364 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
365 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
371 throw new Exception(DI::l10n()->t('Login failed'));
375 * Returns authentication info from various parameters types
377 * User info can be any of the following:
380 * - User email or username or nickname
381 * - User array with at least the uid and the hashed password
383 * @param mixed $user_info
387 private static function getAuthenticationInfo($user_info)
391 if (is_object($user_info) || is_array($user_info)) {
392 if (is_object($user_info)) {
393 $user = (array) $user_info;
400 || !isset($user['password'])
401 || !isset($user['legacy_password'])
403 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
405 } elseif (is_int($user_info) || is_string($user_info)) {
406 if (is_int($user_info)) {
407 $user = DBA::selectFirst(
409 ['uid', 'password', 'legacy_password'],
413 'account_expired' => 0,
414 'account_removed' => 0,
419 $fields = ['uid', 'password', 'legacy_password'];
421 "(`email` = ? OR `username` = ? OR `nickname` = ?)
422 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
423 $user_info, $user_info, $user_info
425 $user = DBA::selectFirst('user', $fields, $condition);
428 if (!DBA::isResult($user)) {
429 throw new Exception(DI::l10n()->t('User not found'));
437 * Generates a human-readable random password
441 public static function generateNewPassword()
443 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
447 * Checks if the provided plaintext password has been exposed or not
449 * @param string $password
453 public static function isPasswordExposed($password)
455 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
456 $cache->changeConfig([
457 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
461 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
463 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
464 } catch (\Exception $e) {
465 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
466 'code' => $e->getCode(),
467 'file' => $e->getFile(),
468 'line' => $e->getLine(),
469 'trace' => $e->getTraceAsString()
477 * Legacy hashing function, kept for password migration purposes
479 * @param string $password
482 private static function hashPasswordLegacy($password)
484 return hash('whirlpool', $password);
488 * Global user password hashing function
490 * @param string $password
494 public static function hashPassword($password)
496 if (!trim($password)) {
497 throw new Exception(DI::l10n()->t('Password can\'t be empty'));
500 return password_hash($password, PASSWORD_DEFAULT);
504 * Updates a user row with a new plaintext password
507 * @param string $password
511 public static function updatePassword($uid, $password)
513 $password = trim($password);
515 if (empty($password)) {
516 throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
519 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
520 throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
523 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
525 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
526 throw new Exception(DI::l10n()->t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
529 return self::updatePasswordHashed($uid, self::hashPassword($password));
533 * Updates a user row with a new hashed password.
534 * Empties the password reset token field just in case.
537 * @param string $pasword_hashed
541 private static function updatePasswordHashed($uid, $pasword_hashed)
544 'password' => $pasword_hashed,
546 'pwdreset_time' => null,
547 'legacy_password' => false
549 return DBA::update('user', $fields, ['uid' => $uid]);
553 * Checks if a nickname is in the list of the forbidden nicknames
555 * Check if a nickname is forbidden from registration on the node by the
556 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
559 * @param string $nickname The nickname that should be checked
560 * @return boolean True is the nickname is blocked on the node
561 * @throws InternalServerErrorException
563 public static function isNicknameBlocked($nickname)
565 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
567 // if the config variable is empty return false
568 if (empty($forbidden_nicknames)) {
572 // check if the nickname is in the list of blocked nicknames
573 $forbidden = explode(',', $forbidden_nicknames);
574 $forbidden = array_map('trim', $forbidden);
575 if (in_array(strtolower($nickname), $forbidden)) {
584 * Catch-all user creation function
586 * Creates a user from the provided data array, either form fields or OpenID.
587 * Required: { username, nickname, email } or { openid_url }
589 * Performs the following:
590 * - Sends to the OpenId auth URL (if relevant)
591 * - Creates new key pairs for crypto
592 * - Create self-contact
593 * - Create profile image
597 * @throws \ErrorException
598 * @throws InternalServerErrorException
599 * @throws \ImagickException
602 public static function create(array $data)
604 $return = ['user' => null, 'password' => ''];
606 $using_invites = DI::config()->get('system', 'invitation_only');
608 $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
609 $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
610 $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
611 $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
612 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
613 $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
614 $password = !empty($data['password']) ? trim($data['password']) : '';
615 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
616 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
617 $blocked = !empty($data['blocked']);
618 $verified = !empty($data['verified']);
619 $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
621 $netpublish = $publish = !empty($data['profile_publish_reg']);
623 if ($password1 != $confirm) {
624 throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
625 } elseif ($password1 != '') {
626 $password = $password1;
629 if ($using_invites) {
631 throw new Exception(DI::l10n()->t('An invitation is required.'));
634 if (!Register::existsByHash($invite_id)) {
635 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
639 /// @todo Check if this part is really needed. We should have fetched all this data in advance
640 if (empty($username) || empty($email) || empty($nickname)) {
642 if (!Network::isUrlValid($openid_url)) {
643 throw new Exception(DI::l10n()->t('Invalid OpenID url'));
645 $_SESSION['register'] = 1;
646 $_SESSION['openid'] = $openid_url;
648 $openid = new LightOpenID(DI::baseUrl()->getHostname());
649 $openid->identity = $openid_url;
650 $openid->returnUrl = DI::baseUrl() . '/openid';
651 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
652 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
654 $authurl = $openid->authUrl();
655 } catch (Exception $e) {
656 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);
658 System::externalRedirect($authurl);
662 throw new Exception(DI::l10n()->t('Please enter the required information.'));
665 if (!Network::isUrlValid($openid_url)) {
669 // collapse multiple spaces in name
670 $username = preg_replace('/ +/', ' ', $username);
672 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
673 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
675 if ($username_min_length > $username_max_length) {
676 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);
677 $tmp = $username_min_length;
678 $username_min_length = $username_max_length;
679 $username_max_length = $tmp;
682 if (mb_strlen($username) < $username_min_length) {
683 throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
686 if (mb_strlen($username) > $username_max_length) {
687 throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
690 // So now we are just looking for a space in the full name.
691 $loose_reg = DI::config()->get('system', 'no_regfullname');
693 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
694 if (strpos($username, ' ') === false) {
695 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
699 if (!Network::isEmailDomainAllowed($email)) {
700 throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
703 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
704 throw new Exception(DI::l10n()->t('Not a valid email address.'));
706 if (self::isNicknameBlocked($nickname)) {
707 throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
710 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
711 throw new Exception(DI::l10n()->t('Cannot use that email.'));
714 // Disallow somebody creating an account using openid that uses the admin email address,
715 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
716 if (DI::config()->get('config', 'admin_email') && strlen($openid_url)) {
717 $adminlist = explode(',', str_replace(' ', '', strtolower(DI::config()->get('config', 'admin_email'))));
718 if (in_array(strtolower($email), $adminlist)) {
719 throw new Exception(DI::l10n()->t('Cannot use that email.'));
723 $nickname = $data['nickname'] = strtolower($nickname);
725 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
726 throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
729 // Check existing and deleted accounts for this nickname.
731 DBA::exists('user', ['nickname' => $nickname])
732 || DBA::exists('userd', ['username' => $nickname])
734 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
737 $new_password = strlen($password) ? $password : User::generateNewPassword();
738 $new_password_encoded = self::hashPassword($new_password);
740 $return['password'] = $new_password;
742 $keys = Crypto::newKeypair(4096);
743 if ($keys === false) {
744 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
747 $prvkey = $keys['prvkey'];
748 $pubkey = $keys['pubkey'];
750 // Create another keypair for signing/verifying salmon protocol messages.
751 $sres = Crypto::newKeypair(512);
752 $sprvkey = $sres['prvkey'];
753 $spubkey = $sres['pubkey'];
755 $insert_result = DBA::insert('user', [
756 'guid' => System::createUUID(),
757 'username' => $username,
758 'password' => $new_password_encoded,
760 'openid' => $openid_url,
761 'nickname' => $nickname,
764 'spubkey' => $spubkey,
765 'sprvkey' => $sprvkey,
766 'verified' => $verified,
767 'blocked' => $blocked,
768 'language' => $language,
770 'register_date' => DateTimeFormat::utcNow(),
771 'default-location' => ''
774 if ($insert_result) {
775 $uid = DBA::lastInsertId();
776 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
778 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
782 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
785 // if somebody clicked submit twice very quickly, they could end up with two accounts
786 // due to race condition. Remove this one.
787 $user_count = DBA::count('user', ['nickname' => $nickname]);
788 if ($user_count > 1) {
789 DBA::delete('user', ['uid' => $uid]);
791 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
794 $insert_result = DBA::insert('profile', [
797 'photo' => DI::baseUrl() . "/photo/profile/{$uid}.jpg",
798 'thumb' => DI::baseUrl() . "/photo/avatar/{$uid}.jpg",
799 'publish' => $publish,
800 'net-publish' => $netpublish,
802 if (!$insert_result) {
803 DBA::delete('user', ['uid' => $uid]);
805 throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
808 // Create the self contact
809 if (!Contact::createSelfFromUserId($uid)) {
810 DBA::delete('user', ['uid' => $uid]);
812 throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
815 // Create a group with no members. This allows somebody to use it
816 // right away as a default group for new contacts.
817 $def_gid = Group::create($uid, DI::l10n()->t('Friends'));
819 DBA::delete('user', ['uid' => $uid]);
821 throw new Exception(DI::l10n()->t('An error occurred creating your default contact group. Please try again.'));
824 $fields = ['def_gid' => $def_gid];
825 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
826 $fields['allow_gid'] = '<' . $def_gid . '>';
829 DBA::update('user', $fields, ['uid' => $uid]);
831 // if we have no OpenID photo try to look up an avatar
832 if (!strlen($photo)) {
833 $photo = Network::lookupAvatarByEmail($email);
836 // unless there is no avatar-addon loaded
837 if (strlen($photo)) {
838 $photo_failure = false;
840 $filename = basename($photo);
841 $img_str = Network::fetchUrl($photo, true);
842 // guess mimetype from headers or filename
843 $type = Images::guessType($photo, true);
845 $Image = new Image($img_str, $type);
846 if ($Image->isValid()) {
847 $Image->scaleToSquare(300);
849 $resource_id = Photo::newResource();
851 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 4);
854 $photo_failure = true;
857 $Image->scaleDown(80);
859 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 5);
862 $photo_failure = true;
865 $Image->scaleDown(48);
867 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 6);
870 $photo_failure = true;
873 if (!$photo_failure) {
874 Photo::update(['profile' => 1], ['resource-id' => $resource_id]);
879 Hook::callAll('register_account', $uid);
881 $return['user'] = $user;
886 * Sets block state for a given user
888 * @param int $uid The user id
889 * @param bool $block Block state (default is true)
891 * @return bool True, if successfully blocked
895 public static function block(int $uid, bool $block = true)
897 return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
901 * Allows a registration based on a hash
903 * @param string $hash
905 * @return bool True, if the allow was successful
907 * @throws InternalServerErrorException
910 public static function allow(string $hash)
912 $register = Register::getByHash($hash);
913 if (!DBA::isResult($register)) {
917 $user = User::getById($register['uid']);
918 if (!DBA::isResult($user)) {
922 Register::deleteByHash($hash);
924 DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]);
926 $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]);
928 if (DBA::isResult($profile) && $profile['net-publish'] && DI::config()->get('system', 'directory')) {
929 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
930 Worker::add(PRIORITY_LOW, "Directory", $url);
933 $l10n = DI::l10n()->withLang($register['language']);
935 return User::sendRegisterOpenEmail(
938 DI::config()->get('config', 'sitename'),
939 DI::baseUrl()->get(),
940 ($register['password'] ?? '') ?: 'Sent in a previous email'
945 * Denys a pending registration
947 * @param string $hash The hash of the pending user
949 * This does not have to go through user_remove() and save the nickname
950 * permanently against re-registration, as the person was not yet
951 * allowed to have friends on this system
953 * @return bool True, if the deny was successfull
956 public static function deny(string $hash)
958 $register = Register::getByHash($hash);
959 if (!DBA::isResult($register)) {
963 $user = User::getById($register['uid']);
964 if (!DBA::isResult($user)) {
968 return DBA::delete('user', ['uid' => $register['uid']]) &&
969 Register::deleteByHash($register['hash']);
973 * Creates a new user based on a minimal set and sends an email to this user
975 * @param string $name The user's name
976 * @param string $email The user's email address
977 * @param string $nick The user's nick name
978 * @param string $lang The user's language (default is english)
980 * @return bool True, if the user was created successfully
981 * @throws InternalServerErrorException
982 * @throws \ErrorException
983 * @throws \ImagickException
985 public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT)
990 throw new InternalServerErrorException('Invalid arguments.');
993 $result = self::create([
1001 $user = $result['user'];
1002 $preamble = Strings::deindent(DI::l10n()->t('
1004 the administrator of %2$s has set up an account for you.'));
1005 $body = Strings::deindent(DI::l10n()->t('
1006 The login details are as follows:
1012 You may change your password from your account "Settings" page after logging
1015 Please take a few moments to review the other account settings on that page.
1017 You may also wish to add some basic information to your default profile
1018 (on the "Profiles" page) so that other people can easily find you.
1020 We recommend setting your full name, adding a profile photo,
1021 adding some profile "keywords" (very useful in making new friends) - and
1022 perhaps what country you live in; if you do not wish to be more specific
1025 We fully respect your right to privacy, and none of these items are necessary.
1026 If you are new and do not know anybody here, they may help
1027 you to make some new and interesting friends.
1029 If you ever want to delete your account, you can do so at %1$s/removeme
1031 Thank you and welcome to %4$s.'));
1033 $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename'));
1034 $body = sprintf($body, DI::baseUrl()->get(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename'));
1036 $email = DI::emailer()
1038 ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body)
1040 ->withRecipient($user['email'])
1042 return DI::emailer()->send($email);
1046 * Sends pending registration confirmation email
1048 * @param array $user User record array
1049 * @param string $sitename
1050 * @param string $siteurl
1051 * @param string $password Plaintext password
1052 * @return NULL|boolean from notification() and email() inherited
1053 * @throws InternalServerErrorException
1055 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
1057 $body = Strings::deindent(DI::l10n()->t(
1060 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
1062 Your login details are as follows:
1075 $email = DI::emailer()
1077 ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
1079 ->withRecipient($user['email'])
1081 return DI::emailer()->send($email);
1085 * Sends registration confirmation
1087 * It's here as a function because the mail is sent from different parts
1089 * @param \Friendica\Core\L10n $l10n The used language
1090 * @param array $user User record array
1091 * @param string $sitename
1092 * @param string $siteurl
1093 * @param string $password Plaintext password
1095 * @return NULL|boolean from notification() and email() inherited
1096 * @throws InternalServerErrorException
1098 public static function sendRegisterOpenEmail(\Friendica\Core\L10n $l10n, $user, $sitename, $siteurl, $password)
1100 $preamble = Strings::deindent($l10n->t(
1103 Thank you for registering at %2$s. Your account has been created.
1108 $body = Strings::deindent($l10n->t(
1110 The login details are as follows:
1116 You may change your password from your account "Settings" page after logging
1119 Please take a few moments to review the other account settings on that page.
1121 You may also wish to add some basic information to your default profile
1122 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1124 We recommend setting your full name, adding a profile photo,
1125 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
1126 perhaps what country you live in; if you do not wish to be more specific
1129 We fully respect your right to privacy, and none of these items are necessary.
1130 If you are new and do not know anybody here, they may help
1131 you to make some new and interesting friends.
1133 If you ever want to delete your account, you can do so at %3$s/removeme
1135 Thank you and welcome to %2$s.',
1143 $email = DI::emailer()
1145 ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1147 ->withRecipient($user['email'])
1149 return DI::emailer()->send($email);
1153 * @param int $uid user to remove
1155 * @throws InternalServerErrorException
1157 public static function remove(int $uid)
1163 Logger::log('Removing user: ' . $uid);
1165 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1167 Hook::callAll('remove_user', $user);
1169 // save username (actually the nickname as it is guaranteed
1170 // unique), so it cannot be re-registered in the future.
1171 DBA::insert('userd', ['username' => $user['nickname']]);
1173 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
1174 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1175 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1177 // Send an update to the directory
1178 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1179 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
1181 // Remove the user relevant data
1182 Worker::add(PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1188 * Return all identities to a user
1190 * @param int $uid The user id
1191 * @return array All identities for this user
1193 * Example for a return:
1197 * 'username' => 'maxmuster',
1198 * 'nickname' => 'Max Mustermann'
1202 * 'username' => 'johndoe',
1203 * 'nickname' => 'John Doe'
1208 public static function identities($uid)
1212 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1213 if (!DBA::isResult($user)) {
1217 if ($user['parent-uid'] == 0) {
1218 // First add our own entry
1220 'uid' => $user['uid'],
1221 'username' => $user['username'],
1222 'nickname' => $user['nickname']
1225 // Then add all the children
1228 ['uid', 'username', 'nickname'],
1229 ['parent-uid' => $user['uid'], 'account_removed' => false]
1231 if (DBA::isResult($r)) {
1232 $identities = array_merge($identities, DBA::toArray($r));
1235 // First entry is our parent
1238 ['uid', 'username', 'nickname'],
1239 ['uid' => $user['parent-uid'], 'account_removed' => false]
1241 if (DBA::isResult($r)) {
1242 $identities = DBA::toArray($r);
1245 // Then add all siblings
1248 ['uid', 'username', 'nickname'],
1249 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1251 if (DBA::isResult($r)) {
1252 $identities = array_merge($identities, DBA::toArray($r));
1257 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1259 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1260 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1263 if (DBA::isResult($r)) {
1264 $identities = array_merge($identities, DBA::toArray($r));
1271 * Returns statistical information about the current users of this node
1277 public static function getStatistics()
1281 'active_users_halfyear' => 0,
1282 'active_users_monthly' => 0,
1285 $userStmt = DBA::p("SELECT `user`.`uid`, `user`.`login_date`, `contact`.`last-item`
1287 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
1288 WHERE `user`.`verified`
1289 AND `user`.`login_date` > ?
1290 AND NOT `user`.`blocked`
1291 AND NOT `user`.`account_removed`
1292 AND NOT `user`.`account_expired`",
1296 if (!DBA::isResult($userStmt)) {
1300 $halfyear = time() - (180 * 24 * 60 * 60);
1301 $month = time() - (30 * 24 * 60 * 60);
1303 while ($user = DBA::fetch($userStmt)) {
1304 $statistics['total_users']++;
1306 if ((strtotime($user['login_date']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1308 $statistics['active_users_halfyear']++;
1311 if ((strtotime($user['login_date']) > $month) || (strtotime($user['last-item']) > $month)
1313 $statistics['active_users_monthly']++;