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 * Returns true if a user record exists with the provided id
105 * @param integer $uid
109 public static function exists($uid)
111 return DBA::exists('user', ['uid' => $uid]);
115 * @param integer $uid
116 * @param array $fields
117 * @return array|boolean User record if it exists, false otherwise
120 public static function getById($uid, array $fields = [])
122 return DBA::selectFirst('user', $fields, ['uid' => $uid]);
126 * Returns a user record based on it's GUID
128 * @param string $guid The guid of the user
129 * @param array $fields The fields to retrieve
130 * @param bool $active True, if only active records are searched
132 * @return array|boolean User record if it exists, false otherwise
135 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
138 $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
140 $cond = ['guid' => $guid];
143 return DBA::selectFirst('user', $fields, $cond);
147 * @param string $nickname
148 * @param array $fields
149 * @return array|boolean User record if it exists, false otherwise
152 public static function getByNickname($nickname, array $fields = [])
154 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
158 * Returns the user id of a given profile URL
162 * @return integer user id
165 public static function getIdForURL($url)
167 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => Strings::normaliseLink($url), 'self' => true]);
168 if (!DBA::isResult($self)) {
176 * Get a user based on its email
178 * @param string $email
179 * @param array $fields
181 * @return array|boolean User record if it exists, false otherwise
185 public static function getByEmail($email, array $fields = [])
187 return DBA::selectFirst('user', $fields, ['email' => $email]);
191 * Fetch the user array of the administrator. The first one if there are several.
193 * @param array $fields
196 public static function getFirstAdmin(array $fields = [])
198 if (!empty(DI::config()->get('config', 'admin_nickname'))) {
199 return self::getByNickname(DI::config()->get('config', 'admin_nickname'), $fields);
200 } elseif (!empty(DI::config()->get('config', 'admin_email'))) {
201 $adminList = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
202 return self::getByEmail($adminList[0], $fields);
209 * Get owner data by user id
212 * @param boolean $check_valid Test if data is invalid and correct it
213 * @return boolean|array
216 public static function getOwnerDataById(int $uid, bool $check_valid = true)
218 if (!empty(self::$owner[$uid])) {
219 return self::$owner[$uid];
222 $owner = DBA::selectFirst('owner-view', [], ['uid' => $uid]);
223 if (!DBA::isResult($owner)) {
224 if (!DBA::exists('user', ['uid' => $uid]) || !$check_valid) {
227 Contact::createSelfFromUserId($uid);
228 $owner = self::getOwnerDataById($uid, false);
231 if (empty($owner['nickname'])) {
239 // Check if the returned data is valid, otherwise fix it. See issue #6122
241 // Check for correct url and normalised nurl
242 $url = DI::baseUrl() . '/profile/' . $owner['nickname'];
243 $repair = ($owner['url'] != $url) || ($owner['nurl'] != Strings::normaliseLink($owner['url']));
246 // Check if "addr" is present and correct
247 $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
248 $repair = ($addr != $owner['addr']);
252 // Check if the avatar field is filled and the photo directs to the correct path
253 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
254 if (DBA::isResult($avatar)) {
255 $repair = empty($owner['avatar']) || !strpos($owner['photo'], $avatar['resource-id']);
260 Contact::updateSelfFromUserID($uid);
261 // Return the corrected data and avoid a loop
262 $owner = self::getOwnerDataById($uid, false);
265 self::$owner[$uid] = $owner;
270 * Get owner data by nick name
273 * @return boolean|array
276 public static function getOwnerDataByNick($nick)
278 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
280 if (!DBA::isResult($user)) {
284 return self::getOwnerDataById($user['uid']);
288 * Returns the default group for a given user and network
290 * @param int $uid User id
291 * @param string $network network name
293 * @return int group id
294 * @throws InternalServerErrorException
296 public static function getDefaultGroup($uid, $network = '')
300 if ($network == Protocol::OSTATUS) {
301 $default_group = DI::pConfig()->get($uid, "ostatus", "default_group");
304 if ($default_group != 0) {
305 return $default_group;
308 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
310 if (DBA::isResult($user)) {
311 $default_group = $user["def_gid"];
314 return $default_group;
319 * Authenticate a user with a clear text password
321 * @param mixed $user_info
322 * @param string $password
323 * @param bool $third_party
324 * @return int|boolean
325 * @deprecated since version 3.6
326 * @see User::getIdFromPasswordAuthentication()
328 public static function authenticate($user_info, $password, $third_party = false)
331 return self::getIdFromPasswordAuthentication($user_info, $password, $third_party);
332 } catch (Exception $ex) {
338 * Authenticate a user with a clear text password
340 * Returns the user id associated with a successful password authentication
342 * @param mixed $user_info
343 * @param string $password
344 * @param bool $third_party
345 * @return int User Id if authentication is successful
348 public static function getIdFromPasswordAuthentication($user_info, $password, $third_party = false)
350 $user = self::getAuthenticationInfo($user_info);
352 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
353 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
354 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
357 } elseif (strpos($user['password'], '$') === false) {
358 //Legacy hash that has not been replaced by a new hash yet
359 if (self::hashPasswordLegacy($password) === $user['password']) {
360 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
364 } elseif (!empty($user['legacy_password'])) {
365 //Legacy hash that has been double-hashed and not replaced by a new hash yet
366 //Warning: `legacy_password` is not necessary in sync with the content of `password`
367 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
368 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
372 } elseif (password_verify($password, $user['password'])) {
374 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
375 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
381 throw new Exception(DI::l10n()->t('Login failed'));
385 * Returns authentication info from various parameters types
387 * User info can be any of the following:
390 * - User email or username or nickname
391 * - User array with at least the uid and the hashed password
393 * @param mixed $user_info
397 private static function getAuthenticationInfo($user_info)
401 if (is_object($user_info) || is_array($user_info)) {
402 if (is_object($user_info)) {
403 $user = (array) $user_info;
410 || !isset($user['password'])
411 || !isset($user['legacy_password'])
413 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
415 } elseif (is_int($user_info) || is_string($user_info)) {
416 if (is_int($user_info)) {
417 $user = DBA::selectFirst(
419 ['uid', 'password', 'legacy_password'],
423 'account_expired' => 0,
424 'account_removed' => 0,
429 $fields = ['uid', 'password', 'legacy_password'];
431 "(`email` = ? OR `username` = ? OR `nickname` = ?)
432 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
433 $user_info, $user_info, $user_info
435 $user = DBA::selectFirst('user', $fields, $condition);
438 if (!DBA::isResult($user)) {
439 throw new Exception(DI::l10n()->t('User not found'));
447 * Generates a human-readable random password
451 public static function generateNewPassword()
453 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
457 * Checks if the provided plaintext password has been exposed or not
459 * @param string $password
463 public static function isPasswordExposed($password)
465 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
466 $cache->changeConfig([
467 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
471 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
473 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
474 } catch (\Exception $e) {
475 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
476 'code' => $e->getCode(),
477 'file' => $e->getFile(),
478 'line' => $e->getLine(),
479 'trace' => $e->getTraceAsString()
487 * Legacy hashing function, kept for password migration purposes
489 * @param string $password
492 private static function hashPasswordLegacy($password)
494 return hash('whirlpool', $password);
498 * Global user password hashing function
500 * @param string $password
504 public static function hashPassword($password)
506 if (!trim($password)) {
507 throw new Exception(DI::l10n()->t('Password can\'t be empty'));
510 return password_hash($password, PASSWORD_DEFAULT);
514 * Updates a user row with a new plaintext password
517 * @param string $password
521 public static function updatePassword($uid, $password)
523 $password = trim($password);
525 if (empty($password)) {
526 throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
529 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
530 throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
533 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
535 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
536 throw new Exception(DI::l10n()->t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
539 return self::updatePasswordHashed($uid, self::hashPassword($password));
543 * Updates a user row with a new hashed password.
544 * Empties the password reset token field just in case.
547 * @param string $pasword_hashed
551 private static function updatePasswordHashed($uid, $pasword_hashed)
554 'password' => $pasword_hashed,
556 'pwdreset_time' => null,
557 'legacy_password' => false
559 return DBA::update('user', $fields, ['uid' => $uid]);
563 * Checks if a nickname is in the list of the forbidden nicknames
565 * Check if a nickname is forbidden from registration on the node by the
566 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
569 * @param string $nickname The nickname that should be checked
570 * @return boolean True is the nickname is blocked on the node
571 * @throws InternalServerErrorException
573 public static function isNicknameBlocked($nickname)
575 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
577 // if the config variable is empty return false
578 if (empty($forbidden_nicknames)) {
582 // check if the nickname is in the list of blocked nicknames
583 $forbidden = explode(',', $forbidden_nicknames);
584 $forbidden = array_map('trim', $forbidden);
585 if (in_array(strtolower($nickname), $forbidden)) {
594 * Catch-all user creation function
596 * Creates a user from the provided data array, either form fields or OpenID.
597 * Required: { username, nickname, email } or { openid_url }
599 * Performs the following:
600 * - Sends to the OpenId auth URL (if relevant)
601 * - Creates new key pairs for crypto
602 * - Create self-contact
603 * - Create profile image
607 * @throws \ErrorException
608 * @throws InternalServerErrorException
609 * @throws \ImagickException
612 public static function create(array $data)
614 $return = ['user' => null, 'password' => ''];
616 $using_invites = DI::config()->get('system', 'invitation_only');
618 $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
619 $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
620 $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
621 $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
622 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
623 $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
624 $password = !empty($data['password']) ? trim($data['password']) : '';
625 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
626 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
627 $blocked = !empty($data['blocked']);
628 $verified = !empty($data['verified']);
629 $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
631 $netpublish = $publish = !empty($data['profile_publish_reg']);
633 if ($password1 != $confirm) {
634 throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
635 } elseif ($password1 != '') {
636 $password = $password1;
639 if ($using_invites) {
641 throw new Exception(DI::l10n()->t('An invitation is required.'));
644 if (!Register::existsByHash($invite_id)) {
645 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
649 /// @todo Check if this part is really needed. We should have fetched all this data in advance
650 if (empty($username) || empty($email) || empty($nickname)) {
652 if (!Network::isUrlValid($openid_url)) {
653 throw new Exception(DI::l10n()->t('Invalid OpenID url'));
655 $_SESSION['register'] = 1;
656 $_SESSION['openid'] = $openid_url;
658 $openid = new LightOpenID(DI::baseUrl()->getHostname());
659 $openid->identity = $openid_url;
660 $openid->returnUrl = DI::baseUrl() . '/openid';
661 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
662 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
664 $authurl = $openid->authUrl();
665 } catch (Exception $e) {
666 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);
668 System::externalRedirect($authurl);
672 throw new Exception(DI::l10n()->t('Please enter the required information.'));
675 if (!Network::isUrlValid($openid_url)) {
679 // collapse multiple spaces in name
680 $username = preg_replace('/ +/', ' ', $username);
682 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
683 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
685 if ($username_min_length > $username_max_length) {
686 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);
687 $tmp = $username_min_length;
688 $username_min_length = $username_max_length;
689 $username_max_length = $tmp;
692 if (mb_strlen($username) < $username_min_length) {
693 throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
696 if (mb_strlen($username) > $username_max_length) {
697 throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
700 // So now we are just looking for a space in the full name.
701 $loose_reg = DI::config()->get('system', 'no_regfullname');
703 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
704 if (strpos($username, ' ') === false) {
705 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
709 if (!Network::isEmailDomainAllowed($email)) {
710 throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
713 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
714 throw new Exception(DI::l10n()->t('Not a valid email address.'));
716 if (self::isNicknameBlocked($nickname)) {
717 throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
720 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
721 throw new Exception(DI::l10n()->t('Cannot use that email.'));
724 // Disallow somebody creating an account using openid that uses the admin email address,
725 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
726 if (DI::config()->get('config', 'admin_email') && strlen($openid_url)) {
727 $adminlist = explode(',', str_replace(' ', '', strtolower(DI::config()->get('config', 'admin_email'))));
728 if (in_array(strtolower($email), $adminlist)) {
729 throw new Exception(DI::l10n()->t('Cannot use that email.'));
733 $nickname = $data['nickname'] = strtolower($nickname);
735 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
736 throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
739 // Check existing and deleted accounts for this nickname.
741 DBA::exists('user', ['nickname' => $nickname])
742 || DBA::exists('userd', ['username' => $nickname])
744 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
747 $new_password = strlen($password) ? $password : User::generateNewPassword();
748 $new_password_encoded = self::hashPassword($new_password);
750 $return['password'] = $new_password;
752 $keys = Crypto::newKeypair(4096);
753 if ($keys === false) {
754 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
757 $prvkey = $keys['prvkey'];
758 $pubkey = $keys['pubkey'];
760 // Create another keypair for signing/verifying salmon protocol messages.
761 $sres = Crypto::newKeypair(512);
762 $sprvkey = $sres['prvkey'];
763 $spubkey = $sres['pubkey'];
765 $insert_result = DBA::insert('user', [
766 'guid' => System::createUUID(),
767 'username' => $username,
768 'password' => $new_password_encoded,
770 'openid' => $openid_url,
771 'nickname' => $nickname,
774 'spubkey' => $spubkey,
775 'sprvkey' => $sprvkey,
776 'verified' => $verified,
777 'blocked' => $blocked,
778 'language' => $language,
780 'register_date' => DateTimeFormat::utcNow(),
781 'default-location' => ''
784 if ($insert_result) {
785 $uid = DBA::lastInsertId();
786 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
788 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
792 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
795 // if somebody clicked submit twice very quickly, they could end up with two accounts
796 // due to race condition. Remove this one.
797 $user_count = DBA::count('user', ['nickname' => $nickname]);
798 if ($user_count > 1) {
799 DBA::delete('user', ['uid' => $uid]);
801 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
804 $insert_result = DBA::insert('profile', [
807 'photo' => DI::baseUrl() . "/photo/profile/{$uid}.jpg",
808 'thumb' => DI::baseUrl() . "/photo/avatar/{$uid}.jpg",
809 'publish' => $publish,
810 'net-publish' => $netpublish,
812 if (!$insert_result) {
813 DBA::delete('user', ['uid' => $uid]);
815 throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
818 // Create the self contact
819 if (!Contact::createSelfFromUserId($uid)) {
820 DBA::delete('user', ['uid' => $uid]);
822 throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
825 // Create a group with no members. This allows somebody to use it
826 // right away as a default group for new contacts.
827 $def_gid = Group::create($uid, DI::l10n()->t('Friends'));
829 DBA::delete('user', ['uid' => $uid]);
831 throw new Exception(DI::l10n()->t('An error occurred creating your default contact group. Please try again.'));
834 $fields = ['def_gid' => $def_gid];
835 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
836 $fields['allow_gid'] = '<' . $def_gid . '>';
839 DBA::update('user', $fields, ['uid' => $uid]);
841 // if we have no OpenID photo try to look up an avatar
842 if (!strlen($photo)) {
843 $photo = Network::lookupAvatarByEmail($email);
846 // unless there is no avatar-addon loaded
847 if (strlen($photo)) {
848 $photo_failure = false;
850 $filename = basename($photo);
851 $curlResult = DI::httpRequest()->get($photo, true);
852 if ($curlResult->isSuccess()) {
853 $img_str = $curlResult->getBody();
854 $type = $curlResult->getContentType();
860 $type = Images::getMimeTypeByData($img_str, $photo, $type);
862 $Image = new Image($img_str, $type);
863 if ($Image->isValid()) {
864 $Image->scaleToSquare(300);
866 $resource_id = Photo::newResource();
868 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 4);
871 $photo_failure = true;
874 $Image->scaleDown(80);
876 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 5);
879 $photo_failure = true;
882 $Image->scaleDown(48);
884 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 6);
887 $photo_failure = true;
890 if (!$photo_failure) {
891 Photo::update(['profile' => 1], ['resource-id' => $resource_id]);
896 Hook::callAll('register_account', $uid);
898 $return['user'] = $user;
903 * Sets block state for a given user
905 * @param int $uid The user id
906 * @param bool $block Block state (default is true)
908 * @return bool True, if successfully blocked
912 public static function block(int $uid, bool $block = true)
914 return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
918 * Allows a registration based on a hash
920 * @param string $hash
922 * @return bool True, if the allow was successful
924 * @throws InternalServerErrorException
927 public static function allow(string $hash)
929 $register = Register::getByHash($hash);
930 if (!DBA::isResult($register)) {
934 $user = User::getById($register['uid']);
935 if (!DBA::isResult($user)) {
939 Register::deleteByHash($hash);
941 DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]);
943 $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]);
945 if (DBA::isResult($profile) && $profile['net-publish'] && DI::config()->get('system', 'directory')) {
946 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
947 Worker::add(PRIORITY_LOW, "Directory", $url);
950 $l10n = DI::l10n()->withLang($register['language']);
952 return User::sendRegisterOpenEmail(
955 DI::config()->get('config', 'sitename'),
956 DI::baseUrl()->get(),
957 ($register['password'] ?? '') ?: 'Sent in a previous email'
962 * Denys a pending registration
964 * @param string $hash The hash of the pending user
966 * This does not have to go through user_remove() and save the nickname
967 * permanently against re-registration, as the person was not yet
968 * allowed to have friends on this system
970 * @return bool True, if the deny was successfull
973 public static function deny(string $hash)
975 $register = Register::getByHash($hash);
976 if (!DBA::isResult($register)) {
980 $user = User::getById($register['uid']);
981 if (!DBA::isResult($user)) {
985 return DBA::delete('user', ['uid' => $register['uid']]) &&
986 Register::deleteByHash($register['hash']);
990 * Creates a new user based on a minimal set and sends an email to this user
992 * @param string $name The user's name
993 * @param string $email The user's email address
994 * @param string $nick The user's nick name
995 * @param string $lang The user's language (default is english)
997 * @return bool True, if the user was created successfully
998 * @throws InternalServerErrorException
999 * @throws \ErrorException
1000 * @throws \ImagickException
1002 public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT)
1007 throw new InternalServerErrorException('Invalid arguments.');
1010 $result = self::create([
1011 'username' => $name,
1013 'nickname' => $nick,
1018 $user = $result['user'];
1019 $preamble = Strings::deindent(DI::l10n()->t('
1021 the administrator of %2$s has set up an account for you.'));
1022 $body = Strings::deindent(DI::l10n()->t('
1023 The login details are as follows:
1029 You may change your password from your account "Settings" page after logging
1032 Please take a few moments to review the other account settings on that page.
1034 You may also wish to add some basic information to your default profile
1035 (on the "Profiles" page) so that other people can easily find you.
1037 We recommend setting your full name, adding a profile photo,
1038 adding some profile "keywords" (very useful in making new friends) - and
1039 perhaps what country you live in; if you do not wish to be more specific
1042 We fully respect your right to privacy, and none of these items are necessary.
1043 If you are new and do not know anybody here, they may help
1044 you to make some new and interesting friends.
1046 If you ever want to delete your account, you can do so at %1$s/removeme
1048 Thank you and welcome to %4$s.'));
1050 $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename'));
1051 $body = sprintf($body, DI::baseUrl()->get(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename'));
1053 $email = DI::emailer()
1055 ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body)
1057 ->withRecipient($user['email'])
1059 return DI::emailer()->send($email);
1063 * Sends pending registration confirmation email
1065 * @param array $user User record array
1066 * @param string $sitename
1067 * @param string $siteurl
1068 * @param string $password Plaintext password
1069 * @return NULL|boolean from notification() and email() inherited
1070 * @throws InternalServerErrorException
1072 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
1074 $body = Strings::deindent(DI::l10n()->t(
1077 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
1079 Your login details are as follows:
1092 $email = DI::emailer()
1094 ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
1096 ->withRecipient($user['email'])
1098 return DI::emailer()->send($email);
1102 * Sends registration confirmation
1104 * It's here as a function because the mail is sent from different parts
1106 * @param \Friendica\Core\L10n $l10n The used language
1107 * @param array $user User record array
1108 * @param string $sitename
1109 * @param string $siteurl
1110 * @param string $password Plaintext password
1112 * @return NULL|boolean from notification() and email() inherited
1113 * @throws InternalServerErrorException
1115 public static function sendRegisterOpenEmail(\Friendica\Core\L10n $l10n, $user, $sitename, $siteurl, $password)
1117 $preamble = Strings::deindent($l10n->t(
1120 Thank you for registering at %2$s. Your account has been created.
1125 $body = Strings::deindent($l10n->t(
1127 The login details are as follows:
1133 You may change your password from your account "Settings" page after logging
1136 Please take a few moments to review the other account settings on that page.
1138 You may also wish to add some basic information to your default profile
1139 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1141 We recommend setting your full name, adding a profile photo,
1142 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
1143 perhaps what country you live in; if you do not wish to be more specific
1146 We fully respect your right to privacy, and none of these items are necessary.
1147 If you are new and do not know anybody here, they may help
1148 you to make some new and interesting friends.
1150 If you ever want to delete your account, you can do so at %3$s/removeme
1152 Thank you and welcome to %2$s.',
1160 $email = DI::emailer()
1162 ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1164 ->withRecipient($user['email'])
1166 return DI::emailer()->send($email);
1170 * @param int $uid user to remove
1172 * @throws InternalServerErrorException
1174 public static function remove(int $uid)
1180 Logger::log('Removing user: ' . $uid);
1182 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1184 Hook::callAll('remove_user', $user);
1186 // save username (actually the nickname as it is guaranteed
1187 // unique), so it cannot be re-registered in the future.
1188 DBA::insert('userd', ['username' => $user['nickname']]);
1190 // The user and related data will be deleted in Friendica\Worker\ExpireAndRemoveUsers
1191 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1192 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1194 // Send an update to the directory
1195 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1196 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
1198 // Remove the user relevant data
1199 Worker::add(PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1205 * Return all identities to a user
1207 * @param int $uid The user id
1208 * @return array All identities for this user
1210 * Example for a return:
1214 * 'username' => 'maxmuster',
1215 * 'nickname' => 'Max Mustermann'
1219 * 'username' => 'johndoe',
1220 * 'nickname' => 'John Doe'
1225 public static function identities($uid)
1229 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1230 if (!DBA::isResult($user)) {
1234 if ($user['parent-uid'] == 0) {
1235 // First add our own entry
1237 'uid' => $user['uid'],
1238 'username' => $user['username'],
1239 'nickname' => $user['nickname']
1242 // Then add all the children
1245 ['uid', 'username', 'nickname'],
1246 ['parent-uid' => $user['uid'], 'account_removed' => false]
1248 if (DBA::isResult($r)) {
1249 $identities = array_merge($identities, DBA::toArray($r));
1252 // First entry is our parent
1255 ['uid', 'username', 'nickname'],
1256 ['uid' => $user['parent-uid'], 'account_removed' => false]
1258 if (DBA::isResult($r)) {
1259 $identities = DBA::toArray($r);
1262 // Then add all siblings
1265 ['uid', 'username', 'nickname'],
1266 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1268 if (DBA::isResult($r)) {
1269 $identities = array_merge($identities, DBA::toArray($r));
1274 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1276 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1277 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1280 if (DBA::isResult($r)) {
1281 $identities = array_merge($identities, DBA::toArray($r));
1288 * Returns statistical information about the current users of this node
1294 public static function getStatistics()
1298 'active_users_halfyear' => 0,
1299 'active_users_monthly' => 0,
1300 'active_users_weekly' => 0,
1303 $userStmt = DBA::select('owner-view', ['uid', 'login_date', 'last-item'],
1304 ["`verified` AND `login_date` > ? AND NOT `blocked`
1305 AND NOT `account_removed` AND NOT `account_expired`",
1306 DBA::NULL_DATETIME]);
1307 if (!DBA::isResult($userStmt)) {
1311 $halfyear = time() - (180 * 24 * 60 * 60);
1312 $month = time() - (30 * 24 * 60 * 60);
1313 $week = time() - (7 * 24 * 60 * 60);
1315 while ($user = DBA::fetch($userStmt)) {
1316 $statistics['total_users']++;
1318 if ((strtotime($user['login_date']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1320 $statistics['active_users_halfyear']++;
1323 if ((strtotime($user['login_date']) > $month) || (strtotime($user['last-item']) > $month)
1325 $statistics['active_users_monthly']++;
1328 if ((strtotime($user['login_date']) > $week) || (strtotime($user['last-item']) > $week)
1330 $statistics['active_users_weekly']++;
1333 DBA::close($userStmt);
1339 * Get all users of the current node
1341 * @param int $start Start count (Default is 0)
1342 * @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE)
1343 * @param string $type The type of users, which should get (all, bocked, removed)
1344 * @param string $order Order of the user list (Default is 'contact.name')
1345 * @param bool $descending Order direction (Default is ascending)
1347 * @return array The list of the users
1350 public static function getList($start = 0, $count = Pager::ITEMS_PER_PAGE, $type = 'all', $order = 'name', bool $descending = false)
1352 $param = ['limit' => [$start, $count], 'order' => [$order => $descending]];
1356 $condition['account_removed'] = false;
1357 $condition['blocked'] = false;
1360 $condition['blocked'] = true;
1363 $condition['account_removed'] = true;
1367 return DBA::selectToArray('owner-view', [], $condition, $param);