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\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 use Friendica\Database\DBA;
33 use Friendica\Model\TwoFactor\AppSpecificPassword;
34 use Friendica\Object\Image;
35 use Friendica\Util\Crypto;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Images;
38 use Friendica\Util\Network;
39 use Friendica\Util\Strings;
40 use Friendica\Worker\Delivery;
44 * This class handles User related functions
51 * PAGE_FLAGS_NORMAL is a typical personal profile account
52 * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
53 * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
54 * write access to wall and comments (no email and not included in page owner's ACL lists)
55 * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
59 const PAGE_FLAGS_NORMAL = 0;
60 const PAGE_FLAGS_SOAPBOX = 1;
61 const PAGE_FLAGS_COMMUNITY = 2;
62 const PAGE_FLAGS_FREELOVE = 3;
63 const PAGE_FLAGS_BLOG = 4;
64 const PAGE_FLAGS_PRVGROUP = 5;
72 * ACCOUNT_TYPE_PERSON - the account belongs to a person
73 * Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
75 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
76 * Associated page type: PAGE_FLAGS_SOAPBOX
78 * ACCOUNT_TYPE_NEWS - the account is a news reflector
79 * Associated page type: PAGE_FLAGS_SOAPBOX
81 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
82 * Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
84 * ACCOUNT_TYPE_RELAY - the account is a relay
85 * This will only be assigned to contacts, not to user accounts
88 const ACCOUNT_TYPE_PERSON = 0;
89 const ACCOUNT_TYPE_ORGANISATION = 1;
90 const ACCOUNT_TYPE_NEWS = 2;
91 const ACCOUNT_TYPE_COMMUNITY = 3;
92 const ACCOUNT_TYPE_RELAY = 4;
98 * Returns true if a user record exists with the provided id
100 * @param integer $uid
104 public static function exists($uid)
106 return DBA::exists('user', ['uid' => $uid]);
110 * @param integer $uid
111 * @param array $fields
112 * @return array|boolean User record if it exists, false otherwise
115 public static function getById($uid, array $fields = [])
117 return DBA::selectFirst('user', $fields, ['uid' => $uid]);
121 * Returns a user record based on it's GUID
123 * @param string $guid The guid of the user
124 * @param array $fields The fields to retrieve
125 * @param bool $active True, if only active records are searched
127 * @return array|boolean User record if it exists, false otherwise
130 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
133 $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
135 $cond = ['guid' => $guid];
138 return DBA::selectFirst('user', $fields, $cond);
142 * @param string $nickname
143 * @param array $fields
144 * @return array|boolean User record if it exists, false otherwise
147 public static function getByNickname($nickname, array $fields = [])
149 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
153 * Returns the user id of a given profile URL
157 * @return integer user id
160 public static function getIdForURL($url)
162 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => Strings::normaliseLink($url), 'self' => true]);
163 if (!DBA::isResult($self)) {
171 * Get a user based on its email
173 * @param string $email
174 * @param array $fields
176 * @return array|boolean User record if it exists, false otherwise
180 public static function getByEmail($email, array $fields = [])
182 return DBA::selectFirst('user', $fields, ['email' => $email]);
186 * Get owner data by user id
189 * @param boolean $check_valid Test if data is invalid and correct it
190 * @return boolean|array
193 public static function getOwnerDataById($uid, $check_valid = true)
195 $r = DBA::fetchFirst(
198 `user`.`prvkey` AS `uprvkey`,
204 `user`.`account-type`,
206 `user`.`account_removed`,
210 ON `user`.`uid` = `contact`.`uid`
211 WHERE `contact`.`uid` = ?
216 if (!DBA::isResult($r)) {
220 if (empty($r['nickname'])) {
228 // Check if the returned data is valid, otherwise fix it. See issue #6122
230 // Check for correct url and normalised nurl
231 $url = DI::baseUrl() . '/profile/' . $r['nickname'];
232 $repair = ($r['url'] != $url) || ($r['nurl'] != Strings::normaliseLink($r['url']));
235 // Check if "addr" is present and correct
236 $addr = $r['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
237 $repair = ($addr != $r['addr']);
241 // Check if the avatar field is filled and the photo directs to the correct path
242 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
243 if (DBA::isResult($avatar)) {
244 $repair = empty($r['avatar']) || !strpos($r['photo'], $avatar['resource-id']);
249 Contact::updateSelfFromUserID($uid);
250 // Return the corrected data and avoid a loop
251 $r = self::getOwnerDataById($uid, false);
258 * Get owner data by nick name
261 * @return boolean|array
264 public static function getOwnerDataByNick($nick)
266 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
268 if (!DBA::isResult($user)) {
272 return self::getOwnerDataById($user['uid']);
276 * Returns the default group for a given user and network
278 * @param int $uid User id
279 * @param string $network network name
281 * @return int group id
282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
284 public static function getDefaultGroup($uid, $network = '')
288 if ($network == Protocol::OSTATUS) {
289 $default_group = DI::pConfig()->get($uid, "ostatus", "default_group");
292 if ($default_group != 0) {
293 return $default_group;
296 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
298 if (DBA::isResult($user)) {
299 $default_group = $user["def_gid"];
302 return $default_group;
307 * Authenticate a user with a clear text password
309 * @param mixed $user_info
310 * @param string $password
311 * @param bool $third_party
312 * @return int|boolean
313 * @deprecated since version 3.6
314 * @see User::getIdFromPasswordAuthentication()
316 public static function authenticate($user_info, $password, $third_party = false)
319 return self::getIdFromPasswordAuthentication($user_info, $password, $third_party);
320 } catch (Exception $ex) {
326 * Authenticate a user with a clear text password
328 * Returns the user id associated with a successful password authentication
330 * @param mixed $user_info
331 * @param string $password
332 * @param bool $third_party
333 * @return int User Id if authentication is successful
336 public static function getIdFromPasswordAuthentication($user_info, $password, $third_party = false)
338 $user = self::getAuthenticationInfo($user_info);
340 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
341 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
342 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
345 } elseif (strpos($user['password'], '$') === false) {
346 //Legacy hash that has not been replaced by a new hash yet
347 if (self::hashPasswordLegacy($password) === $user['password']) {
348 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
352 } elseif (!empty($user['legacy_password'])) {
353 //Legacy hash that has been double-hashed and not replaced by a new hash yet
354 //Warning: `legacy_password` is not necessary in sync with the content of `password`
355 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
356 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
360 } elseif (password_verify($password, $user['password'])) {
362 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
363 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
369 throw new Exception(DI::l10n()->t('Login failed'));
373 * Returns authentication info from various parameters types
375 * User info can be any of the following:
378 * - User email or username or nickname
379 * - User array with at least the uid and the hashed password
381 * @param mixed $user_info
385 private static function getAuthenticationInfo($user_info)
389 if (is_object($user_info) || is_array($user_info)) {
390 if (is_object($user_info)) {
391 $user = (array) $user_info;
398 || !isset($user['password'])
399 || !isset($user['legacy_password'])
401 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
403 } elseif (is_int($user_info) || is_string($user_info)) {
404 if (is_int($user_info)) {
405 $user = DBA::selectFirst(
407 ['uid', 'password', 'legacy_password'],
411 'account_expired' => 0,
412 'account_removed' => 0,
417 $fields = ['uid', 'password', 'legacy_password'];
419 "(`email` = ? OR `username` = ? OR `nickname` = ?)
420 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
421 $user_info, $user_info, $user_info
423 $user = DBA::selectFirst('user', $fields, $condition);
426 if (!DBA::isResult($user)) {
427 throw new Exception(DI::l10n()->t('User not found'));
435 * Generates a human-readable random password
439 public static function generateNewPassword()
441 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
445 * Checks if the provided plaintext password has been exposed or not
447 * @param string $password
451 public static function isPasswordExposed($password)
453 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
454 $cache->changeConfig([
455 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
459 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
461 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
462 } catch (\Exception $e) {
463 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
464 'code' => $e->getCode(),
465 'file' => $e->getFile(),
466 'line' => $e->getLine(),
467 'trace' => $e->getTraceAsString()
475 * Legacy hashing function, kept for password migration purposes
477 * @param string $password
480 private static function hashPasswordLegacy($password)
482 return hash('whirlpool', $password);
486 * Global user password hashing function
488 * @param string $password
492 public static function hashPassword($password)
494 if (!trim($password)) {
495 throw new Exception(DI::l10n()->t('Password can\'t be empty'));
498 return password_hash($password, PASSWORD_DEFAULT);
502 * Updates a user row with a new plaintext password
505 * @param string $password
509 public static function updatePassword($uid, $password)
511 $password = trim($password);
513 if (empty($password)) {
514 throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
517 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
518 throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
521 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
523 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
524 throw new Exception(DI::l10n()->t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
527 return self::updatePasswordHashed($uid, self::hashPassword($password));
531 * Updates a user row with a new hashed password.
532 * Empties the password reset token field just in case.
535 * @param string $pasword_hashed
539 private static function updatePasswordHashed($uid, $pasword_hashed)
542 'password' => $pasword_hashed,
544 'pwdreset_time' => null,
545 'legacy_password' => false
547 return DBA::update('user', $fields, ['uid' => $uid]);
551 * Checks if a nickname is in the list of the forbidden nicknames
553 * Check if a nickname is forbidden from registration on the node by the
554 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
557 * @param string $nickname The nickname that should be checked
558 * @return boolean True is the nickname is blocked on the node
559 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
561 public static function isNicknameBlocked($nickname)
563 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
565 // if the config variable is empty return false
566 if (empty($forbidden_nicknames)) {
570 // check if the nickname is in the list of blocked nicknames
571 $forbidden = explode(',', $forbidden_nicknames);
572 $forbidden = array_map('trim', $forbidden);
573 if (in_array(strtolower($nickname), $forbidden)) {
582 * Catch-all user creation function
584 * Creates a user from the provided data array, either form fields or OpenID.
585 * Required: { username, nickname, email } or { openid_url }
587 * Performs the following:
588 * - Sends to the OpenId auth URL (if relevant)
589 * - Creates new key pairs for crypto
590 * - Create self-contact
591 * - Create profile image
595 * @throws \ErrorException
596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
597 * @throws \ImagickException
600 public static function create(array $data)
602 $return = ['user' => null, 'password' => ''];
604 $using_invites = DI::config()->get('system', 'invitation_only');
606 $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
607 $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
608 $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
609 $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
610 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
611 $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
612 $password = !empty($data['password']) ? trim($data['password']) : '';
613 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
614 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
615 $blocked = !empty($data['blocked']);
616 $verified = !empty($data['verified']);
617 $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
619 $netpublish = $publish = !empty($data['profile_publish_reg']);
621 if ($password1 != $confirm) {
622 throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
623 } elseif ($password1 != '') {
624 $password = $password1;
627 if ($using_invites) {
629 throw new Exception(DI::l10n()->t('An invitation is required.'));
632 if (!Register::existsByHash($invite_id)) {
633 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
637 /// @todo Check if this part is really needed. We should have fetched all this data in advance
638 if (empty($username) || empty($email) || empty($nickname)) {
640 if (!Network::isUrlValid($openid_url)) {
641 throw new Exception(DI::l10n()->t('Invalid OpenID url'));
643 $_SESSION['register'] = 1;
644 $_SESSION['openid'] = $openid_url;
646 $openid = new LightOpenID(DI::baseUrl()->getHostname());
647 $openid->identity = $openid_url;
648 $openid->returnUrl = DI::baseUrl() . '/openid';
649 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
650 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
652 $authurl = $openid->authUrl();
653 } catch (Exception $e) {
654 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);
656 System::externalRedirect($authurl);
660 throw new Exception(DI::l10n()->t('Please enter the required information.'));
663 if (!Network::isUrlValid($openid_url)) {
667 // collapse multiple spaces in name
668 $username = preg_replace('/ +/', ' ', $username);
670 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
671 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
673 if ($username_min_length > $username_max_length) {
674 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);
675 $tmp = $username_min_length;
676 $username_min_length = $username_max_length;
677 $username_max_length = $tmp;
680 if (mb_strlen($username) < $username_min_length) {
681 throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
684 if (mb_strlen($username) > $username_max_length) {
685 throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
688 // So now we are just looking for a space in the full name.
689 $loose_reg = DI::config()->get('system', 'no_regfullname');
691 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
692 if (strpos($username, ' ') === false) {
693 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
697 if (!Network::isEmailDomainAllowed($email)) {
698 throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
701 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
702 throw new Exception(DI::l10n()->t('Not a valid email address.'));
704 if (self::isNicknameBlocked($nickname)) {
705 throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
708 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
709 throw new Exception(DI::l10n()->t('Cannot use that email.'));
712 // Disallow somebody creating an account using openid that uses the admin email address,
713 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
714 if (DI::config()->get('config', 'admin_email') && strlen($openid_url)) {
715 $adminlist = explode(',', str_replace(' ', '', strtolower(DI::config()->get('config', 'admin_email'))));
716 if (in_array(strtolower($email), $adminlist)) {
717 throw new Exception(DI::l10n()->t('Cannot use that email.'));
721 $nickname = $data['nickname'] = strtolower($nickname);
723 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
724 throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
727 // Check existing and deleted accounts for this nickname.
729 DBA::exists('user', ['nickname' => $nickname])
730 || DBA::exists('userd', ['username' => $nickname])
732 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
735 $new_password = strlen($password) ? $password : User::generateNewPassword();
736 $new_password_encoded = self::hashPassword($new_password);
738 $return['password'] = $new_password;
740 $keys = Crypto::newKeypair(4096);
741 if ($keys === false) {
742 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
745 $prvkey = $keys['prvkey'];
746 $pubkey = $keys['pubkey'];
748 // Create another keypair for signing/verifying salmon protocol messages.
749 $sres = Crypto::newKeypair(512);
750 $sprvkey = $sres['prvkey'];
751 $spubkey = $sres['pubkey'];
753 $insert_result = DBA::insert('user', [
754 'guid' => System::createUUID(),
755 'username' => $username,
756 'password' => $new_password_encoded,
758 'openid' => $openid_url,
759 'nickname' => $nickname,
762 'spubkey' => $spubkey,
763 'sprvkey' => $sprvkey,
764 'verified' => $verified,
765 'blocked' => $blocked,
766 'language' => $language,
768 'register_date' => DateTimeFormat::utcNow(),
769 'default-location' => ''
772 if ($insert_result) {
773 $uid = DBA::lastInsertId();
774 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
776 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
780 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
783 // if somebody clicked submit twice very quickly, they could end up with two accounts
784 // due to race condition. Remove this one.
785 $user_count = DBA::count('user', ['nickname' => $nickname]);
786 if ($user_count > 1) {
787 DBA::delete('user', ['uid' => $uid]);
789 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
792 $insert_result = DBA::insert('profile', [
795 'photo' => DI::baseUrl() . "/photo/profile/{$uid}.jpg",
796 'thumb' => DI::baseUrl() . "/photo/avatar/{$uid}.jpg",
797 'publish' => $publish,
798 'net-publish' => $netpublish,
800 if (!$insert_result) {
801 DBA::delete('user', ['uid' => $uid]);
803 throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
806 // Create the self contact
807 if (!Contact::createSelfFromUserId($uid)) {
808 DBA::delete('user', ['uid' => $uid]);
810 throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
813 // Create a group with no members. This allows somebody to use it
814 // right away as a default group for new contacts.
815 $def_gid = Group::create($uid, DI::l10n()->t('Friends'));
817 DBA::delete('user', ['uid' => $uid]);
819 throw new Exception(DI::l10n()->t('An error occurred creating your default contact group. Please try again.'));
822 $fields = ['def_gid' => $def_gid];
823 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
824 $fields['allow_gid'] = '<' . $def_gid . '>';
827 DBA::update('user', $fields, ['uid' => $uid]);
829 // if we have no OpenID photo try to look up an avatar
830 if (!strlen($photo)) {
831 $photo = Network::lookupAvatarByEmail($email);
834 // unless there is no avatar-addon loaded
835 if (strlen($photo)) {
836 $photo_failure = false;
838 $filename = basename($photo);
839 $img_str = Network::fetchUrl($photo, true);
840 // guess mimetype from headers or filename
841 $type = Images::guessType($photo, true);
843 $Image = new Image($img_str, $type);
844 if ($Image->isValid()) {
845 $Image->scaleToSquare(300);
847 $resource_id = Photo::newResource();
849 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 4);
852 $photo_failure = true;
855 $Image->scaleDown(80);
857 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 5);
860 $photo_failure = true;
863 $Image->scaleDown(48);
865 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 6);
868 $photo_failure = true;
871 if (!$photo_failure) {
872 Photo::update(['profile' => 1], ['resource-id' => $resource_id]);
877 Hook::callAll('register_account', $uid);
879 $return['user'] = $user;
884 * Sets block state for a given user
886 * @param int $uid The user id
887 * @param bool $block Block state (default is true)
889 * @return bool True, if successfully blocked
893 public static function block(int $uid, bool $block = true)
895 return DBA::update('user', ['blocked' => 0], ['uid' => $uid]);
899 * Sends pending registration confirmation email
901 * @param array $user User record array
902 * @param string $sitename
903 * @param string $siteurl
904 * @param string $password Plaintext password
905 * @return NULL|boolean from notification() and email() inherited
906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
908 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
910 $body = Strings::deindent(DI::l10n()->t(
913 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
915 Your login details are as follows:
928 $email = DI::emailer()
930 ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
932 ->withRecipient($user['email'])
934 return DI::emailer()->send($email);
938 * Sends registration confirmation
940 * It's here as a function because the mail is sent from different parts
942 * @param \Friendica\Core\L10n $l10n The used language
943 * @param array $user User record array
944 * @param string $sitename
945 * @param string $siteurl
946 * @param string $password Plaintext password
948 * @return NULL|boolean from notification() and email() inherited
949 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
951 public static function sendRegisterOpenEmail(\Friendica\Core\L10n $l10n, $user, $sitename, $siteurl, $password)
953 $preamble = Strings::deindent($l10n->t(
956 Thank you for registering at %2$s. Your account has been created.
961 $body = Strings::deindent($l10n->t(
963 The login details are as follows:
969 You may change your password from your account "Settings" page after logging
972 Please take a few moments to review the other account settings on that page.
974 You may also wish to add some basic information to your default profile
975 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
977 We recommend setting your full name, adding a profile photo,
978 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
979 perhaps what country you live in; if you do not wish to be more specific
982 We fully respect your right to privacy, and none of these items are necessary.
983 If you are new and do not know anybody here, they may help
984 you to make some new and interesting friends.
986 If you ever want to delete your account, you can do so at %3$s/removeme
988 Thank you and welcome to %2$s.',
996 $email = DI::emailer()
998 ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1000 ->withRecipient($user['email'])
1002 return DI::emailer()->send($email);
1006 * @param object $uid user to remove
1008 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1010 public static function remove($uid)
1016 Logger::log('Removing user: ' . $uid);
1018 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1020 Hook::callAll('remove_user', $user);
1022 // save username (actually the nickname as it is guaranteed
1023 // unique), so it cannot be re-registered in the future.
1024 DBA::insert('userd', ['username' => $user['nickname']]);
1026 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
1027 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1028 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1030 // Send an update to the directory
1031 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1032 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
1034 // Remove the user relevant data
1035 Worker::add(PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1041 * Return all identities to a user
1043 * @param int $uid The user id
1044 * @return array All identities for this user
1046 * Example for a return:
1050 * 'username' => 'maxmuster',
1051 * 'nickname' => 'Max Mustermann'
1055 * 'username' => 'johndoe',
1056 * 'nickname' => 'John Doe'
1061 public static function identities($uid)
1065 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1066 if (!DBA::isResult($user)) {
1070 if ($user['parent-uid'] == 0) {
1071 // First add our own entry
1073 'uid' => $user['uid'],
1074 'username' => $user['username'],
1075 'nickname' => $user['nickname']
1078 // Then add all the children
1081 ['uid', 'username', 'nickname'],
1082 ['parent-uid' => $user['uid'], 'account_removed' => false]
1084 if (DBA::isResult($r)) {
1085 $identities = array_merge($identities, DBA::toArray($r));
1088 // First entry is our parent
1091 ['uid', 'username', 'nickname'],
1092 ['uid' => $user['parent-uid'], 'account_removed' => false]
1094 if (DBA::isResult($r)) {
1095 $identities = DBA::toArray($r);
1098 // Then add all siblings
1101 ['uid', 'username', 'nickname'],
1102 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1104 if (DBA::isResult($r)) {
1105 $identities = array_merge($identities, DBA::toArray($r));
1110 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1112 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1113 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1116 if (DBA::isResult($r)) {
1117 $identities = array_merge($identities, DBA::toArray($r));
1124 * Returns statistical information about the current users of this node
1130 public static function getStatistics()
1134 'active_users_halfyear' => 0,
1135 'active_users_monthly' => 0,
1138 $userStmt = DBA::p("SELECT `user`.`uid`, `user`.`login_date`, `contact`.`last-item`
1140 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
1141 WHERE `user`.`verified`
1142 AND `user`.`login_date` > ?
1143 AND NOT `user`.`blocked`
1144 AND NOT `user`.`account_removed`
1145 AND NOT `user`.`account_expired`",
1149 if (!DBA::isResult($userStmt)) {
1153 $halfyear = time() - (180 * 24 * 60 * 60);
1154 $month = time() - (30 * 24 * 60 * 60);
1156 while ($user = DBA::fetch($userStmt)) {
1157 $statistics['total_users']++;
1159 if ((strtotime($user['login_date']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1161 $statistics['active_users_halfyear']++;
1164 if ((strtotime($user['login_date']) > $month) || (strtotime($user['last-item']) > $month)
1166 $statistics['active_users_monthly']++;