3 * @file src/Model/User.php
4 * @brief This file includes the User class with user related database functions
6 namespace Friendica\Model;
8 use DivineOmega\PasswordExposed;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\Hook;
13 use Friendica\Core\L10n;
14 use Friendica\Core\Logger;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Photo;
21 use Friendica\Object\Image;
22 use Friendica\Util\Crypto;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Network;
25 use Friendica\Util\Strings;
29 * @brief This class handles User related functions
34 * Returns true if a user record exists with the provided id
39 public static function exists($uid)
41 return DBA::exists('user', ['uid' => $uid]);
46 * @return array|boolean User record if it exists, false otherwise
48 public static function getById($uid)
50 return DBA::selectFirst('user', [], ['uid' => $uid]);
54 * @brief Returns the user id of a given profile URL
58 * @return integer user id
60 public static function getIdForURL($url)
62 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => Strings::normaliseLink($url), 'self' => true]);
63 if (!DBA::isResult($self)) {
71 * @brief Get owner data by user id
74 * @return boolean|array
76 public static function getOwnerDataById($uid) {
77 $r = DBA::fetchFirst("SELECT
79 `user`.`prvkey` AS `uprvkey`,
85 `user`.`account-type`,
89 ON `user`.`uid` = `contact`.`uid`
90 WHERE `contact`.`uid` = ?
95 if (!DBA::isResult($r)) {
99 if (empty($r['nickname'])) {
103 // Check if the returned data is valid, otherwise fix it. See issue #6122
104 $url = System::baseUrl() . '/profile/' . $r['nickname'];
105 $addr = $r['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
107 if (($addr != $r['addr']) || ($r['url'] != $url) || ($r['nurl'] != Strings::normaliseLink($r['url']))) {
108 Contact::updateSelfFromUserID($uid);
115 * @brief Get owner data by nick name
118 * @return boolean|array
120 public static function getOwnerDataByNick($nick)
122 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
124 if (!DBA::isResult($user)) {
128 return self::getOwnerDataById($user['uid']);
132 * @brief Returns the default group for a given user and network
134 * @param int $uid User id
135 * @param string $network network name
137 * @return int group id
139 public static function getDefaultGroup($uid, $network = '')
143 if ($network == Protocol::OSTATUS) {
144 $default_group = PConfig::get($uid, "ostatus", "default_group");
147 if ($default_group != 0) {
148 return $default_group;
151 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
153 if (DBA::isResult($user)) {
154 $default_group = $user["def_gid"];
157 return $default_group;
162 * Authenticate a user with a clear text password
164 * @brief Authenticate a user with a clear text password
165 * @param mixed $user_info
166 * @param string $password
167 * @return int|boolean
168 * @deprecated since version 3.6
169 * @see User::getIdFromPasswordAuthentication()
171 public static function authenticate($user_info, $password)
174 return self::getIdFromPasswordAuthentication($user_info, $password);
175 } catch (Exception $ex) {
181 * Returns the user id associated with a successful password authentication
183 * @brief Authenticate a user with a clear text password
184 * @param mixed $user_info
185 * @param string $password
186 * @return int User Id if authentication is successful
189 public static function getIdFromPasswordAuthentication($user_info, $password)
191 $user = self::getAuthenticationInfo($user_info);
193 if (strpos($user['password'], '$') === false) {
194 //Legacy hash that has not been replaced by a new hash yet
195 if (self::hashPasswordLegacy($password) === $user['password']) {
196 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
200 } elseif (!empty($user['legacy_password'])) {
201 //Legacy hash that has been double-hashed and not replaced by a new hash yet
202 //Warning: `legacy_password` is not necessary in sync with the content of `password`
203 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
204 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
208 } elseif (password_verify($password, $user['password'])) {
210 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
211 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
217 throw new Exception(L10n::t('Login failed'));
221 * Returns authentication info from various parameters types
223 * User info can be any of the following:
226 * - User email or username or nickname
227 * - User array with at least the uid and the hashed password
229 * @param mixed $user_info
233 private static function getAuthenticationInfo($user_info)
237 if (is_object($user_info) || is_array($user_info)) {
238 if (is_object($user_info)) {
239 $user = (array) $user_info;
244 if (!isset($user['uid'])
245 || !isset($user['password'])
246 || !isset($user['legacy_password'])
248 throw new Exception(L10n::t('Not enough information to authenticate'));
250 } elseif (is_int($user_info) || is_string($user_info)) {
251 if (is_int($user_info)) {
252 $user = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'],
256 'account_expired' => 0,
257 'account_removed' => 0,
262 $fields = ['uid', 'password', 'legacy_password'];
263 $condition = ["(`email` = ? OR `username` = ? OR `nickname` = ?)
264 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
265 $user_info, $user_info, $user_info];
266 $user = DBA::selectFirst('user', $fields, $condition);
269 if (!DBA::isResult($user)) {
270 throw new Exception(L10n::t('User not found'));
278 * Generates a human-readable random password
282 public static function generateNewPassword()
284 return ucfirst(Strings::getRandomName(8)) . mt_rand(1000, 9999);
288 * Checks if the provided plaintext password has been exposed or not
290 * @param string $password
293 public static function isPasswordExposed($password)
295 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
296 $cache->changeConfig([
297 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
300 $PasswordExposedCHecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
302 return $PasswordExposedCHecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
306 * Legacy hashing function, kept for password migration purposes
308 * @param string $password
311 private static function hashPasswordLegacy($password)
313 return hash('whirlpool', $password);
317 * Global user password hashing function
319 * @param string $password
323 public static function hashPassword($password)
325 if (!trim($password)) {
326 throw new Exception(L10n::t('Password can\'t be empty'));
329 return password_hash($password, PASSWORD_DEFAULT);
333 * Updates a user row with a new plaintext password
336 * @param string $password
340 public static function updatePassword($uid, $password)
342 $password = trim($password);
344 if (empty($password)) {
345 throw new Exception(L10n::t('Empty passwords are not allowed.'));
348 if (!Config::get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
349 throw new Exception(L10n::t('The new password has been exposed in a public data dump, please choose another.'));
352 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
354 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
355 throw new Exception(L10n::t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
358 return self::updatePasswordHashed($uid, self::hashPassword($password));
362 * Updates a user row with a new hashed password.
363 * Empties the password reset token field just in case.
366 * @param string $pasword_hashed
369 private static function updatePasswordHashed($uid, $pasword_hashed)
372 'password' => $pasword_hashed,
374 'pwdreset_time' => null,
375 'legacy_password' => false
377 return DBA::update('user', $fields, ['uid' => $uid]);
381 * @brief Checks if a nickname is in the list of the forbidden nicknames
383 * Check if a nickname is forbidden from registration on the node by the
384 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
387 * @param string $nickname The nickname that should be checked
388 * @return boolean True is the nickname is blocked on the node
390 public static function isNicknameBlocked($nickname)
392 $forbidden_nicknames = Config::get('system', 'forbidden_nicknames', '');
394 // if the config variable is empty return false
395 if (empty($forbidden_nicknames)) {
399 // check if the nickname is in the list of blocked nicknames
400 $forbidden = explode(',', $forbidden_nicknames);
401 $forbidden = array_map('trim', $forbidden);
402 if (in_array(strtolower($nickname), $forbidden)) {
411 * @brief Catch-all user creation function
413 * Creates a user from the provided data array, either form fields or OpenID.
414 * Required: { username, nickname, email } or { openid_url }
416 * Performs the following:
417 * - Sends to the OpenId auth URL (if relevant)
418 * - Creates new key pairs for crypto
419 * - Create self-contact
420 * - Create profile image
424 * @throws \ErrorException
425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
428 public static function create(array $data)
431 $return = ['user' => null, 'password' => ''];
433 $using_invites = Config::get('system', 'invitation_only');
434 $num_invites = Config::get('system', 'number_invites');
436 $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
437 $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
438 $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
439 $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
440 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
441 $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
442 $password = !empty($data['password']) ? trim($data['password']) : '';
443 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
444 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
445 $blocked = !empty($data['blocked']);
446 $verified = !empty($data['verified']);
447 $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
449 $publish = !empty($data['profile_publish_reg']);
450 $netpublish = $publish && Config::get('system', 'directory');
452 if ($password1 != $confirm) {
453 throw new Exception(L10n::t('Passwords do not match. Password unchanged.'));
454 } elseif ($password1 != '') {
455 $password = $password1;
458 if ($using_invites) {
460 throw new Exception(L10n::t('An invitation is required.'));
463 if (!Register::existsByHash($invite_id)) {
464 throw new Exception(L10n::t('Invitation could not be verified.'));
468 if (empty($username) || empty($email) || empty($nickname)) {
470 if (!Network::isUrlValid($openid_url)) {
471 throw new Exception(L10n::t('Invalid OpenID url'));
473 $_SESSION['register'] = 1;
474 $_SESSION['openid'] = $openid_url;
476 $openid = new LightOpenID($a->getHostName());
477 $openid->identity = $openid_url;
478 $openid->returnUrl = System::baseUrl() . '/openid';
479 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
480 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
482 $authurl = $openid->authUrl();
483 } catch (Exception $e) {
484 throw new Exception(L10n::t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . EOL . EOL . L10n::t('The error message was:') . $e->getMessage(), 0, $e);
486 System::externalRedirect($authurl);
490 throw new Exception(L10n::t('Please enter the required information.'));
493 if (!Network::isUrlValid($openid_url)) {
499 // collapse multiple spaces in name
500 $username = preg_replace('/ +/', ' ', $username);
502 $username_min_length = max(1, min(64, intval(Config::get('system', 'username_min_length', 3))));
503 $username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48))));
505 if ($username_min_length > $username_max_length) {
506 Logger::log(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);
507 $tmp = $username_min_length;
508 $username_min_length = $username_max_length;
509 $username_max_length = $tmp;
512 if (mb_strlen($username) < $username_min_length) {
513 throw new Exception(L10n::tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
516 if (mb_strlen($username) > $username_max_length) {
517 throw new Exception(L10n::tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
520 // So now we are just looking for a space in the full name.
521 $loose_reg = Config::get('system', 'no_regfullname');
523 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
524 if (strpos($username, ' ') === false) {
525 throw new Exception(L10n::t("That doesn't appear to be your full (First Last) name."));
529 if (!Network::isEmailDomainAllowed($email)) {
530 throw new Exception(L10n::t('Your email domain is not among those allowed on this site.'));
533 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
534 throw new Exception(L10n::t('Not a valid email address.'));
536 if (self::isNicknameBlocked($nickname)) {
537 throw new Exception(L10n::t('The nickname was blocked from registration by the nodes admin.'));
540 if (Config::get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
541 throw new Exception(L10n::t('Cannot use that email.'));
544 // Disallow somebody creating an account using openid that uses the admin email address,
545 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
546 if (Config::get('config', 'admin_email') && strlen($openid_url)) {
547 $adminlist = explode(',', str_replace(' ', '', strtolower(Config::get('config', 'admin_email'))));
548 if (in_array(strtolower($email), $adminlist)) {
549 throw new Exception(L10n::t('Cannot use that email.'));
553 $nickname = $data['nickname'] = strtolower($nickname);
555 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
556 throw new Exception(L10n::t('Your nickname can only contain a-z, 0-9 and _.'));
559 // Check existing and deleted accounts for this nickname.
560 if (DBA::exists('user', ['nickname' => $nickname])
561 || DBA::exists('userd', ['username' => $nickname])
563 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
566 $new_password = strlen($password) ? $password : User::generateNewPassword();
567 $new_password_encoded = self::hashPassword($new_password);
569 $return['password'] = $new_password;
571 $keys = Crypto::newKeypair(4096);
572 if ($keys === false) {
573 throw new Exception(L10n::t('SERIOUS ERROR: Generation of security keys failed.'));
576 $prvkey = $keys['prvkey'];
577 $pubkey = $keys['pubkey'];
579 // Create another keypair for signing/verifying salmon protocol messages.
580 $sres = Crypto::newKeypair(512);
581 $sprvkey = $sres['prvkey'];
582 $spubkey = $sres['pubkey'];
584 $insert_result = DBA::insert('user', [
585 'guid' => System::createUUID(),
586 'username' => $username,
587 'password' => $new_password_encoded,
589 'openid' => $openid_url,
590 'nickname' => $nickname,
593 'spubkey' => $spubkey,
594 'sprvkey' => $sprvkey,
595 'verified' => $verified,
596 'blocked' => $blocked,
597 'language' => $language,
599 'register_date' => DateTimeFormat::utcNow(),
600 'default-location' => ''
603 if ($insert_result) {
604 $uid = DBA::lastInsertId();
605 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
607 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
611 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
614 // if somebody clicked submit twice very quickly, they could end up with two accounts
615 // due to race condition. Remove this one.
616 $user_count = DBA::count('user', ['nickname' => $nickname]);
617 if ($user_count > 1) {
618 DBA::delete('user', ['uid' => $uid]);
620 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
623 $insert_result = DBA::insert('profile', [
626 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
627 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
628 'publish' => $publish,
630 'net-publish' => $netpublish,
631 'profile-name' => L10n::t('default')
633 if (!$insert_result) {
634 DBA::delete('user', ['uid' => $uid]);
636 throw new Exception(L10n::t('An error occurred creating your default profile. Please try again.'));
639 // Create the self contact
640 if (!Contact::createSelfFromUserId($uid)) {
641 DBA::delete('user', ['uid' => $uid]);
643 throw new Exception(L10n::t('An error occurred creating your self contact. Please try again.'));
646 // Create a group with no members. This allows somebody to use it
647 // right away as a default group for new contacts.
648 $def_gid = Group::create($uid, L10n::t('Friends'));
650 DBA::delete('user', ['uid' => $uid]);
652 throw new Exception(L10n::t('An error occurred creating your default contact group. Please try again.'));
655 $fields = ['def_gid' => $def_gid];
656 if (Config::get('system', 'newuser_private') && $def_gid) {
657 $fields['allow_gid'] = '<' . $def_gid . '>';
660 DBA::update('user', $fields, ['uid' => $uid]);
662 // if we have no OpenID photo try to look up an avatar
663 if (!strlen($photo)) {
664 $photo = Network::lookupAvatarByEmail($email);
667 // unless there is no avatar-addon loaded
668 if (strlen($photo)) {
669 $photo_failure = false;
671 $filename = basename($photo);
672 $img_str = Network::fetchUrl($photo, true);
673 // guess mimetype from headers or filename
674 $type = Image::guessType($photo, true);
676 $Image = new Image($img_str, $type);
677 if ($Image->isValid()) {
678 $Image->scaleToSquare(300);
680 $hash = Photo::newResource();
682 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 4);
685 $photo_failure = true;
688 $Image->scaleDown(80);
690 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 5);
693 $photo_failure = true;
696 $Image->scaleDown(48);
698 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 6);
701 $photo_failure = true;
704 if (!$photo_failure) {
705 Photo::update(['profile' => 1], ['resource-id' => $hash]);
710 Addon::callHooks('register_account', $uid);
712 $return['user'] = $user;
717 * @brief Sends pending registration confirmation email
719 * @param array $user User record array
720 * @param string $sitename
721 * @param string $siteurl
722 * @param string $password Plaintext password
723 * @return NULL|boolean from notification() and email() inherited
725 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
727 $body = Strings::deindent(L10n::t('
729 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
731 Your login details are as follows:
737 $user['username'], $sitename, $siteurl, $user['nickname'], $password
740 return notification([
741 'type' => SYSTEM_EMAIL,
742 'uid' => $user['uid'],
743 'to_email' => $user['email'],
744 'subject' => L10n::t('Registration at %s', $sitename),
750 * @brief Sends registration confirmation
752 * It's here as a function because the mail is sent from different parts
754 * @param array $user User record array
755 * @param string $sitename
756 * @param string $siteurl
757 * @param string $password Plaintext password
758 * @return NULL|boolean from notification() and email() inherited
760 public static function sendRegisterOpenEmail($user, $sitename, $siteurl, $password)
762 $preamble = Strings::deindent(L10n::t('
764 Thank you for registering at %2$s. Your account has been created.
766 $user['username'], $sitename
768 $body = Strings::deindent(L10n::t('
769 The login details are as follows:
775 You may change your password from your account "Settings" page after logging
778 Please take a few moments to review the other account settings on that page.
780 You may also wish to add some basic information to your default profile
781 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
783 We recommend setting your full name, adding a profile photo,
784 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
785 perhaps what country you live in; if you do not wish to be more specific
788 We fully respect your right to privacy, and none of these items are necessary.
789 If you are new and do not know anybody here, they may help
790 you to make some new and interesting friends.
792 If you ever want to delete your account, you can do so at %3$s/removeme
794 Thank you and welcome to %2$s.',
795 $user['nickname'], $sitename, $siteurl, $user['username'], $password
798 return notification([
799 'uid' => $user['uid'],
800 'language' => $user['language'],
801 'type' => SYSTEM_EMAIL,
802 'to_email' => $user['email'],
803 'subject' => L10n::t('Registration details for %s', $sitename),
804 'preamble' => $preamble,
810 * @param object $uid user to remove
813 public static function remove($uid)
821 Logger::log('Removing user: ' . $uid);
823 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
825 Hook::callAll('remove_user', $user);
827 // save username (actually the nickname as it is guaranteed
828 // unique), so it cannot be re-registered in the future.
829 DBA::insert('userd', ['username' => $user['nickname']]);
831 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
832 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
833 Worker::add(PRIORITY_HIGH, 'Notifier', 'removeme', $uid);
835 // Send an update to the directory
836 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
837 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
839 // Remove the user relevant data
840 Worker::add(PRIORITY_LOW, 'RemoveUser', $uid);
846 * Return all identities to a user
848 * @param int $uid The user id
849 * @return array All identities for this user
851 * Example for a return:
855 * 'username' => 'maxmuster',
856 * 'nickname' => 'Max Mustermann'
860 * 'username' => 'johndoe',
861 * 'nickname' => 'John Doe'
865 public static function identities($uid)
869 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
870 if (!DBA::isResult($user)) {
874 if ($user['parent-uid'] == 0) {
875 // First add our own entry
876 $identities = [['uid' => $user['uid'],
877 'username' => $user['username'],
878 'nickname' => $user['nickname']]];
880 // Then add all the children
881 $r = DBA::select('user', ['uid', 'username', 'nickname'],
882 ['parent-uid' => $user['uid'], 'account_removed' => false]);
883 if (DBA::isResult($r)) {
884 $identities = array_merge($identities, DBA::toArray($r));
887 // First entry is our parent
888 $r = DBA::select('user', ['uid', 'username', 'nickname'],
889 ['uid' => $user['parent-uid'], 'account_removed' => false]);
890 if (DBA::isResult($r)) {
891 $identities = DBA::toArray($r);
894 // Then add all siblings
895 $r = DBA::select('user', ['uid', 'username', 'nickname'],
896 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]);
897 if (DBA::isResult($r)) {
898 $identities = array_merge($identities, DBA::toArray($r));
902 $r = DBA::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
904 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
905 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
908 if (DBA::isResult($r)) {
909 $identities = array_merge($identities, DBA::toArray($r));