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\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Object\Image;
19 use Friendica\Util\Crypto;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
24 require_once 'boot.php';
25 require_once 'include/dba.php';
26 require_once 'include/enotify.php';
27 require_once 'include/text.php';
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' => normalise_link($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)) {
102 * @brief Get owner data by nick name
105 * @return boolean|array
107 public static function getOwnerDataByNick($nick)
109 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
111 if (!DBA::isResult($user)) {
115 return self::getOwnerDataById($user['uid']);
119 * @brief Returns the default group for a given user and network
121 * @param int $uid User id
122 * @param string $network network name
124 * @return int group id
126 public static function getDefaultGroup($uid, $network = '')
130 if ($network == Protocol::OSTATUS) {
131 $default_group = PConfig::get($uid, "ostatus", "default_group");
134 if ($default_group != 0) {
135 return $default_group;
138 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
140 if (DBA::isResult($user)) {
141 $default_group = $user["def_gid"];
144 return $default_group;
149 * Authenticate a user with a clear text password
151 * @brief Authenticate a user with a clear text password
152 * @param mixed $user_info
153 * @param string $password
154 * @return int|boolean
155 * @deprecated since version 3.6
156 * @see User::getIdFromPasswordAuthentication()
158 public static function authenticate($user_info, $password)
161 return self::getIdFromPasswordAuthentication($user_info, $password);
162 } catch (Exception $ex) {
168 * Returns the user id associated with a successful password authentication
170 * @brief Authenticate a user with a clear text password
171 * @param mixed $user_info
172 * @param string $password
173 * @return int User Id if authentication is successful
176 public static function getIdFromPasswordAuthentication($user_info, $password)
178 $user = self::getAuthenticationInfo($user_info);
180 if (strpos($user['password'], '$') === false) {
181 //Legacy hash that has not been replaced by a new hash yet
182 if (self::hashPasswordLegacy($password) === $user['password']) {
183 self::updatePassword($user['uid'], $password);
187 } elseif (!empty($user['legacy_password'])) {
188 //Legacy hash that has been double-hashed and not replaced by a new hash yet
189 //Warning: `legacy_password` is not necessary in sync with the content of `password`
190 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
191 self::updatePassword($user['uid'], $password);
195 } elseif (password_verify($password, $user['password'])) {
197 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
198 self::updatePassword($user['uid'], $password);
204 throw new Exception(L10n::t('Login failed'));
208 * Returns authentication info from various parameters types
210 * User info can be any of the following:
213 * - User email or username or nickname
214 * - User array with at least the uid and the hashed password
216 * @param mixed $user_info
220 private static function getAuthenticationInfo($user_info)
224 if (is_object($user_info) || is_array($user_info)) {
225 if (is_object($user_info)) {
226 $user = (array) $user_info;
231 if (!isset($user['uid'])
232 || !isset($user['password'])
233 || !isset($user['legacy_password'])
235 throw new Exception(L10n::t('Not enough information to authenticate'));
237 } elseif (is_int($user_info) || is_string($user_info)) {
238 if (is_int($user_info)) {
239 $user = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'],
243 'account_expired' => 0,
244 'account_removed' => 0,
249 $fields = ['uid', 'password', 'legacy_password'];
250 $condition = ["(`email` = ? OR `username` = ? OR `nickname` = ?)
251 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
252 $user_info, $user_info, $user_info];
253 $user = DBA::selectFirst('user', $fields, $condition);
256 if (!DBA::isResult($user)) {
257 throw new Exception(L10n::t('User not found'));
265 * Generates a human-readable random password
269 public static function generateNewPassword()
271 return autoname(6) . mt_rand(100, 9999);
275 * Checks if the provided plaintext password has been exposed or not
277 * @param string $password
280 public static function isPasswordExposed($password)
282 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
283 $cache->changeConfig([
284 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
287 $PasswordExposedCHecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
289 return $PasswordExposedCHecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
293 * Legacy hashing function, kept for password migration purposes
295 * @param string $password
298 private static function hashPasswordLegacy($password)
300 return hash('whirlpool', $password);
304 * Global user password hashing function
306 * @param string $password
309 public static function hashPassword($password)
311 if (!trim($password)) {
312 throw new Exception(L10n::t('Password can\'t be empty'));
315 return password_hash($password, PASSWORD_DEFAULT);
319 * Updates a user row with a new plaintext password
322 * @param string $password
325 public static function updatePassword($uid, $password)
327 return self::updatePasswordHashed($uid, self::hashPassword($password));
331 * Updates a user row with a new hashed password.
332 * Empties the password reset token field just in case.
335 * @param string $pasword_hashed
338 private static function updatePasswordHashed($uid, $pasword_hashed)
341 'password' => $pasword_hashed,
343 'pwdreset_time' => null,
344 'legacy_password' => false
346 return DBA::update('user', $fields, ['uid' => $uid]);
350 * @brief Checks if a nickname is in the list of the forbidden nicknames
352 * Check if a nickname is forbidden from registration on the node by the
353 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
356 * @param string $nickname The nickname that should be checked
357 * @return boolean True is the nickname is blocked on the node
359 public static function isNicknameBlocked($nickname)
361 $forbidden_nicknames = Config::get('system', 'forbidden_nicknames', '');
363 // if the config variable is empty return false
364 if (empty($forbidden_nicknames)) {
368 // check if the nickname is in the list of blocked nicknames
369 $forbidden = explode(',', $forbidden_nicknames);
370 $forbidden = array_map('trim', $forbidden);
371 if (in_array(strtolower($nickname), $forbidden)) {
380 * @brief Catch-all user creation function
382 * Creates a user from the provided data array, either form fields or OpenID.
383 * Required: { username, nickname, email } or { openid_url }
385 * Performs the following:
386 * - Sends to the OpenId auth URL (if relevant)
387 * - Creates new key pairs for crypto
388 * - Create self-contact
389 * - Create profile image
395 public static function create(array $data)
398 $return = ['user' => null, 'password' => ''];
400 $using_invites = Config::get('system', 'invitation_only');
401 $num_invites = Config::get('system', 'number_invites');
403 $invite_id = !empty($data['invite_id']) ? notags(trim($data['invite_id'])) : '';
404 $username = !empty($data['username']) ? notags(trim($data['username'])) : '';
405 $nickname = !empty($data['nickname']) ? notags(trim($data['nickname'])) : '';
406 $email = !empty($data['email']) ? notags(trim($data['email'])) : '';
407 $openid_url = !empty($data['openid_url']) ? notags(trim($data['openid_url'])) : '';
408 $photo = !empty($data['photo']) ? notags(trim($data['photo'])) : '';
409 $password = !empty($data['password']) ? trim($data['password']) : '';
410 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
411 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
412 $blocked = !empty($data['blocked']) ? intval($data['blocked']) : 0;
413 $verified = !empty($data['verified']) ? intval($data['verified']) : 0;
414 $language = !empty($data['language']) ? notags(trim($data['language'])) : 'en';
416 $publish = !empty($data['profile_publish_reg']) && intval($data['profile_publish_reg']) ? 1 : 0;
417 $netpublish = strlen(Config::get('system', 'directory')) ? $publish : 0;
419 if ($password1 != $confirm) {
420 throw new Exception(L10n::t('Passwords do not match. Password unchanged.'));
421 } elseif ($password1 != '') {
422 $password = $password1;
425 if ($using_invites) {
427 throw new Exception(L10n::t('An invitation is required.'));
430 if (!Register::existsByHash($invite_id)) {
431 throw new Exception(L10n::t('Invitation could not be verified.'));
435 if (empty($username) || empty($email) || empty($nickname)) {
437 if (!Network::isUrlValid($openid_url)) {
438 throw new Exception(L10n::t('Invalid OpenID url'));
440 $_SESSION['register'] = 1;
441 $_SESSION['openid'] = $openid_url;
443 $openid = new LightOpenID($a->getHostName());
444 $openid->identity = $openid_url;
445 $openid->returnUrl = System::baseUrl() . '/openid';
446 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
447 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
449 $authurl = $openid->authUrl();
450 } catch (Exception $e) {
451 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);
453 System::externalRedirect($authurl);
457 throw new Exception(L10n::t('Please enter the required information.'));
460 if (!Network::isUrlValid($openid_url)) {
466 // collapse multiple spaces in name
467 $username = preg_replace('/ +/', ' ', $username);
469 $username_min_length = max(1, min(64, intval(Config::get('system', 'username_min_length', 3))));
470 $username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48))));
472 if ($username_min_length > $username_max_length) {
473 logger(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);
474 $tmp = $username_min_length;
475 $username_min_length = $username_max_length;
476 $username_max_length = $tmp;
479 if (mb_strlen($username) < $username_min_length) {
480 throw new Exception(L10n::tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
483 if (mb_strlen($username) > $username_max_length) {
484 throw new Exception(L10n::tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
487 // So now we are just looking for a space in the full name.
488 $loose_reg = Config::get('system', 'no_regfullname');
490 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
491 if (strpos($username, ' ') === false) {
492 throw new Exception(L10n::t("That doesn't appear to be your full (First Last) name."));
496 if (!Network::isEmailDomainAllowed($email)) {
497 throw new Exception(L10n::t('Your email domain is not among those allowed on this site.'));
500 if (!valid_email($email) || !Network::isEmailDomainValid($email)) {
501 throw new Exception(L10n::t('Not a valid email address.'));
503 if (self::isNicknameBlocked($nickname)) {
504 throw new Exception(L10n::t('The nickname was blocked from registration by the nodes admin.'));
507 if (Config::get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
508 throw new Exception(L10n::t('Cannot use that email.'));
511 // Disallow somebody creating an account using openid that uses the admin email address,
512 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
513 if (Config::get('config', 'admin_email') && strlen($openid_url)) {
514 $adminlist = explode(',', str_replace(' ', '', strtolower(Config::get('config', 'admin_email'))));
515 if (in_array(strtolower($email), $adminlist)) {
516 throw new Exception(L10n::t('Cannot use that email.'));
520 $nickname = $data['nickname'] = strtolower($nickname);
522 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
523 throw new Exception(L10n::t('Your nickname can only contain a-z, 0-9 and _.'));
526 // Check existing and deleted accounts for this nickname.
527 if (DBA::exists('user', ['nickname' => $nickname])
528 || DBA::exists('userd', ['username' => $nickname])
530 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
533 $new_password = strlen($password) ? $password : User::generateNewPassword();
534 $new_password_encoded = self::hashPassword($new_password);
536 $return['password'] = $new_password;
538 $keys = Crypto::newKeypair(4096);
539 if ($keys === false) {
540 throw new Exception(L10n::t('SERIOUS ERROR: Generation of security keys failed.'));
543 $prvkey = $keys['prvkey'];
544 $pubkey = $keys['pubkey'];
546 // Create another keypair for signing/verifying salmon protocol messages.
547 $sres = Crypto::newKeypair(512);
548 $sprvkey = $sres['prvkey'];
549 $spubkey = $sres['pubkey'];
551 $insert_result = DBA::insert('user', [
552 'guid' => System::createUUID(),
553 'username' => $username,
554 'password' => $new_password_encoded,
556 'openid' => $openid_url,
557 'nickname' => $nickname,
560 'spubkey' => $spubkey,
561 'sprvkey' => $sprvkey,
562 'verified' => $verified,
563 'blocked' => $blocked,
564 'language' => $language,
566 'register_date' => DateTimeFormat::utcNow(),
567 'default-location' => ''
570 if ($insert_result) {
571 $uid = DBA::lastInsertId();
572 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
574 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
578 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
581 // if somebody clicked submit twice very quickly, they could end up with two accounts
582 // due to race condition. Remove this one.
583 $user_count = DBA::count('user', ['nickname' => $nickname]);
584 if ($user_count > 1) {
585 DBA::delete('user', ['uid' => $uid]);
587 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
590 $insert_result = DBA::insert('profile', [
593 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
594 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
595 'publish' => $publish,
597 'net-publish' => $netpublish,
598 'profile-name' => L10n::t('default')
600 if (!$insert_result) {
601 DBA::delete('user', ['uid' => $uid]);
603 throw new Exception(L10n::t('An error occurred creating your default profile. Please try again.'));
606 // Create the self contact
607 if (!Contact::createSelfFromUserId($uid)) {
608 DBA::delete('user', ['uid' => $uid]);
610 throw new Exception(L10n::t('An error occurred creating your self contact. Please try again.'));
613 // Create a group with no members. This allows somebody to use it
614 // right away as a default group for new contacts.
615 $def_gid = Group::create($uid, L10n::t('Friends'));
617 DBA::delete('user', ['uid' => $uid]);
619 throw new Exception(L10n::t('An error occurred creating your default contact group. Please try again.'));
622 $fields = ['def_gid' => $def_gid];
623 if (Config::get('system', 'newuser_private') && $def_gid) {
624 $fields['allow_gid'] = '<' . $def_gid . '>';
627 DBA::update('user', $fields, ['uid' => $uid]);
629 // if we have no OpenID photo try to look up an avatar
630 if (!strlen($photo)) {
631 $photo = Network::lookupAvatarByEmail($email);
634 // unless there is no avatar-addon loaded
635 if (strlen($photo)) {
636 $photo_failure = false;
638 $filename = basename($photo);
639 $img_str = Network::fetchUrl($photo, true);
640 // guess mimetype from headers or filename
641 $type = Image::guessType($photo, true);
643 $Image = new Image($img_str, $type);
644 if ($Image->isValid()) {
645 $Image->scaleToSquare(175);
647 $hash = Photo::newResource();
649 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 4);
652 $photo_failure = true;
655 $Image->scaleDown(80);
657 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 5);
660 $photo_failure = true;
663 $Image->scaleDown(48);
665 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 6);
668 $photo_failure = true;
671 if (!$photo_failure) {
672 DBA::update('photo', ['profile' => 1], ['resource-id' => $hash]);
677 Addon::callHooks('register_account', $uid);
679 $return['user'] = $user;
684 * @brief Sends pending registration confirmation email
686 * @param array $user User record array
687 * @param string $sitename
688 * @param string $siteurl
689 * @param string $password Plaintext password
690 * @return NULL|boolean from notification() and email() inherited
692 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
694 $body = deindent(L10n::t('
696 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
698 Your login details are as follows:
704 $user['username'], $sitename, $siteurl, $user['nickname'], $password
707 return notification([
708 'type' => SYSTEM_EMAIL,
709 'uid' => $user['uid'],
710 'to_email' => $user['email'],
711 'subject' => L10n::t('Registration at %s', $sitename),
717 * @brief Sends registration confirmation
719 * It's here as a function because the mail is sent from different parts
721 * @param array $user User record array
722 * @param string $sitename
723 * @param string $siteurl
724 * @param string $password Plaintext password
725 * @return NULL|boolean from notification() and email() inherited
727 public static function sendRegisterOpenEmail($user, $sitename, $siteurl, $password)
729 $preamble = deindent(L10n::t('
731 Thank you for registering at %2$s. Your account has been created.
733 $preamble, $user['username'], $sitename
735 $body = deindent(L10n::t('
736 The login details are as follows:
742 You may change your password from your account "Settings" page after logging
745 Please take a few moments to review the other account settings on that page.
747 You may also wish to add some basic information to your default profile
748 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
750 We recommend setting your full name, adding a profile photo,
751 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
752 perhaps what country you live in; if you do not wish to be more specific
755 We fully respect your right to privacy, and none of these items are necessary.
756 If you are new and do not know anybody here, they may help
757 you to make some new and interesting friends.
759 If you ever want to delete your account, you can do so at %3$s/removeme
761 Thank you and welcome to %2$s.',
762 $user['email'], $sitename, $siteurl, $user['username'], $password
765 return notification([
766 'uid' => $user['uid'],
767 'language' => $user['language'],
768 'type' => SYSTEM_EMAIL,
769 'to_email' => $user['email'],
770 'subject' => L10n::t('Registration details for %s', $sitename),
771 'preamble' => $preamble,
777 * @param object $uid user to remove
780 public static function remove($uid)
788 logger('Removing user: ' . $uid);
790 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
792 Addon::callHooks('remove_user', $user);
794 // save username (actually the nickname as it is guaranteed
795 // unique), so it cannot be re-registered in the future.
796 DBA::insert('userd', ['username' => $user['nickname']]);
798 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
799 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc(DateTimeFormat::utcNow() . " + 7 day")], ['uid' => $uid]);
800 Worker::add(PRIORITY_HIGH, "Notifier", "removeme", $uid);
802 // Send an update to the directory
803 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
804 Worker::add(PRIORITY_LOW, "Directory", $self['url']);
806 // Remove the user relevant data
807 Worker::add(PRIORITY_LOW, "RemoveUser", $uid);
809 if ($uid == local_user()) {
810 unset($_SESSION['authenticated']);
811 unset($_SESSION['uid']);
812 $a->internalRedirect();