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\Logger;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Protocol;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Object\Image;
20 use Friendica\Util\Crypto;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
25 require_once 'boot.php';
26 require_once 'include/dba.php';
27 require_once 'include/enotify.php';
28 require_once 'include/text.php';
30 * @brief This class handles User related functions
35 * Returns true if a user record exists with the provided id
40 public static function exists($uid)
42 return DBA::exists('user', ['uid' => $uid]);
47 * @return array|boolean User record if it exists, false otherwise
49 public static function getById($uid)
51 return DBA::selectFirst('user', [], ['uid' => $uid]);
55 * @brief Returns the user id of a given profile URL
59 * @return integer user id
61 public static function getIdForURL($url)
63 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($url), 'self' => true]);
64 if (!DBA::isResult($self)) {
72 * @brief Get owner data by user id
75 * @return boolean|array
77 public static function getOwnerDataById($uid) {
78 $r = DBA::fetchFirst("SELECT
80 `user`.`prvkey` AS `uprvkey`,
86 `user`.`account-type`,
90 ON `user`.`uid` = `contact`.`uid`
91 WHERE `contact`.`uid` = ?
96 if (!DBA::isResult($r)) {
103 * @brief Get owner data by nick name
106 * @return boolean|array
108 public static function getOwnerDataByNick($nick)
110 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
112 if (!DBA::isResult($user)) {
116 return self::getOwnerDataById($user['uid']);
120 * @brief Returns the default group for a given user and network
122 * @param int $uid User id
123 * @param string $network network name
125 * @return int group id
127 public static function getDefaultGroup($uid, $network = '')
131 if ($network == Protocol::OSTATUS) {
132 $default_group = PConfig::get($uid, "ostatus", "default_group");
135 if ($default_group != 0) {
136 return $default_group;
139 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
141 if (DBA::isResult($user)) {
142 $default_group = $user["def_gid"];
145 return $default_group;
150 * Authenticate a user with a clear text password
152 * @brief Authenticate a user with a clear text password
153 * @param mixed $user_info
154 * @param string $password
155 * @return int|boolean
156 * @deprecated since version 3.6
157 * @see User::getIdFromPasswordAuthentication()
159 public static function authenticate($user_info, $password)
162 return self::getIdFromPasswordAuthentication($user_info, $password);
163 } catch (Exception $ex) {
169 * Returns the user id associated with a successful password authentication
171 * @brief Authenticate a user with a clear text password
172 * @param mixed $user_info
173 * @param string $password
174 * @return int User Id if authentication is successful
177 public static function getIdFromPasswordAuthentication($user_info, $password)
179 $user = self::getAuthenticationInfo($user_info);
181 if (strpos($user['password'], '$') === false) {
182 //Legacy hash that has not been replaced by a new hash yet
183 if (self::hashPasswordLegacy($password) === $user['password']) {
184 self::updatePassword($user['uid'], $password);
188 } elseif (!empty($user['legacy_password'])) {
189 //Legacy hash that has been double-hashed and not replaced by a new hash yet
190 //Warning: `legacy_password` is not necessary in sync with the content of `password`
191 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
192 self::updatePassword($user['uid'], $password);
196 } elseif (password_verify($password, $user['password'])) {
198 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
199 self::updatePassword($user['uid'], $password);
205 throw new Exception(L10n::t('Login failed'));
209 * Returns authentication info from various parameters types
211 * User info can be any of the following:
214 * - User email or username or nickname
215 * - User array with at least the uid and the hashed password
217 * @param mixed $user_info
221 private static function getAuthenticationInfo($user_info)
225 if (is_object($user_info) || is_array($user_info)) {
226 if (is_object($user_info)) {
227 $user = (array) $user_info;
232 if (!isset($user['uid'])
233 || !isset($user['password'])
234 || !isset($user['legacy_password'])
236 throw new Exception(L10n::t('Not enough information to authenticate'));
238 } elseif (is_int($user_info) || is_string($user_info)) {
239 if (is_int($user_info)) {
240 $user = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'],
244 'account_expired' => 0,
245 'account_removed' => 0,
250 $fields = ['uid', 'password', 'legacy_password'];
251 $condition = ["(`email` = ? OR `username` = ? OR `nickname` = ?)
252 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
253 $user_info, $user_info, $user_info];
254 $user = DBA::selectFirst('user', $fields, $condition);
257 if (!DBA::isResult($user)) {
258 throw new Exception(L10n::t('User not found'));
266 * Generates a human-readable random password
270 public static function generateNewPassword()
272 return autoname(6) . mt_rand(100, 9999);
276 * Checks if the provided plaintext password has been exposed or not
278 * @param string $password
281 public static function isPasswordExposed($password)
283 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
284 $cache->changeConfig([
285 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
288 $PasswordExposedCHecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
290 return $PasswordExposedCHecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
294 * Legacy hashing function, kept for password migration purposes
296 * @param string $password
299 private static function hashPasswordLegacy($password)
301 return hash('whirlpool', $password);
305 * Global user password hashing function
307 * @param string $password
310 public static function hashPassword($password)
312 if (!trim($password)) {
313 throw new Exception(L10n::t('Password can\'t be empty'));
316 return password_hash($password, PASSWORD_DEFAULT);
320 * Updates a user row with a new plaintext password
323 * @param string $password
326 public static function updatePassword($uid, $password)
328 return self::updatePasswordHashed($uid, self::hashPassword($password));
332 * Updates a user row with a new hashed password.
333 * Empties the password reset token field just in case.
336 * @param string $pasword_hashed
339 private static function updatePasswordHashed($uid, $pasword_hashed)
342 'password' => $pasword_hashed,
344 'pwdreset_time' => null,
345 'legacy_password' => false
347 return DBA::update('user', $fields, ['uid' => $uid]);
351 * @brief Checks if a nickname is in the list of the forbidden nicknames
353 * Check if a nickname is forbidden from registration on the node by the
354 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
357 * @param string $nickname The nickname that should be checked
358 * @return boolean True is the nickname is blocked on the node
360 public static function isNicknameBlocked($nickname)
362 $forbidden_nicknames = Config::get('system', 'forbidden_nicknames', '');
364 // if the config variable is empty return false
365 if (empty($forbidden_nicknames)) {
369 // check if the nickname is in the list of blocked nicknames
370 $forbidden = explode(',', $forbidden_nicknames);
371 $forbidden = array_map('trim', $forbidden);
372 if (in_array(strtolower($nickname), $forbidden)) {
381 * @brief Catch-all user creation function
383 * Creates a user from the provided data array, either form fields or OpenID.
384 * Required: { username, nickname, email } or { openid_url }
386 * Performs the following:
387 * - Sends to the OpenId auth URL (if relevant)
388 * - Creates new key pairs for crypto
389 * - Create self-contact
390 * - Create profile image
396 public static function create(array $data)
399 $return = ['user' => null, 'password' => ''];
401 $using_invites = Config::get('system', 'invitation_only');
402 $num_invites = Config::get('system', 'number_invites');
404 $invite_id = !empty($data['invite_id']) ? notags(trim($data['invite_id'])) : '';
405 $username = !empty($data['username']) ? notags(trim($data['username'])) : '';
406 $nickname = !empty($data['nickname']) ? notags(trim($data['nickname'])) : '';
407 $email = !empty($data['email']) ? notags(trim($data['email'])) : '';
408 $openid_url = !empty($data['openid_url']) ? notags(trim($data['openid_url'])) : '';
409 $photo = !empty($data['photo']) ? notags(trim($data['photo'])) : '';
410 $password = !empty($data['password']) ? trim($data['password']) : '';
411 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
412 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
413 $blocked = !empty($data['blocked']) ? intval($data['blocked']) : 0;
414 $verified = !empty($data['verified']) ? intval($data['verified']) : 0;
415 $language = !empty($data['language']) ? notags(trim($data['language'])) : 'en';
417 $publish = !empty($data['profile_publish_reg']) && intval($data['profile_publish_reg']) ? 1 : 0;
418 $netpublish = strlen(Config::get('system', 'directory')) ? $publish : 0;
420 if ($password1 != $confirm) {
421 throw new Exception(L10n::t('Passwords do not match. Password unchanged.'));
422 } elseif ($password1 != '') {
423 $password = $password1;
426 if ($using_invites) {
428 throw new Exception(L10n::t('An invitation is required.'));
431 if (!Register::existsByHash($invite_id)) {
432 throw new Exception(L10n::t('Invitation could not be verified.'));
436 if (empty($username) || empty($email) || empty($nickname)) {
438 if (!Network::isUrlValid($openid_url)) {
439 throw new Exception(L10n::t('Invalid OpenID url'));
441 $_SESSION['register'] = 1;
442 $_SESSION['openid'] = $openid_url;
444 $openid = new LightOpenID($a->getHostName());
445 $openid->identity = $openid_url;
446 $openid->returnUrl = System::baseUrl() . '/openid';
447 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
448 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
450 $authurl = $openid->authUrl();
451 } catch (Exception $e) {
452 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);
454 System::externalRedirect($authurl);
458 throw new Exception(L10n::t('Please enter the required information.'));
461 if (!Network::isUrlValid($openid_url)) {
467 // collapse multiple spaces in name
468 $username = preg_replace('/ +/', ' ', $username);
470 $username_min_length = max(1, min(64, intval(Config::get('system', 'username_min_length', 3))));
471 $username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48))));
473 if ($username_min_length > $username_max_length) {
474 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);
475 $tmp = $username_min_length;
476 $username_min_length = $username_max_length;
477 $username_max_length = $tmp;
480 if (mb_strlen($username) < $username_min_length) {
481 throw new Exception(L10n::tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
484 if (mb_strlen($username) > $username_max_length) {
485 throw new Exception(L10n::tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
488 // So now we are just looking for a space in the full name.
489 $loose_reg = Config::get('system', 'no_regfullname');
491 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
492 if (strpos($username, ' ') === false) {
493 throw new Exception(L10n::t("That doesn't appear to be your full (First Last) name."));
497 if (!Network::isEmailDomainAllowed($email)) {
498 throw new Exception(L10n::t('Your email domain is not among those allowed on this site.'));
501 if (!valid_email($email) || !Network::isEmailDomainValid($email)) {
502 throw new Exception(L10n::t('Not a valid email address.'));
504 if (self::isNicknameBlocked($nickname)) {
505 throw new Exception(L10n::t('The nickname was blocked from registration by the nodes admin.'));
508 if (Config::get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
509 throw new Exception(L10n::t('Cannot use that email.'));
512 // Disallow somebody creating an account using openid that uses the admin email address,
513 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
514 if (Config::get('config', 'admin_email') && strlen($openid_url)) {
515 $adminlist = explode(',', str_replace(' ', '', strtolower(Config::get('config', 'admin_email'))));
516 if (in_array(strtolower($email), $adminlist)) {
517 throw new Exception(L10n::t('Cannot use that email.'));
521 $nickname = $data['nickname'] = strtolower($nickname);
523 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
524 throw new Exception(L10n::t('Your nickname can only contain a-z, 0-9 and _.'));
527 // Check existing and deleted accounts for this nickname.
528 if (DBA::exists('user', ['nickname' => $nickname])
529 || DBA::exists('userd', ['username' => $nickname])
531 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
534 $new_password = strlen($password) ? $password : User::generateNewPassword();
535 $new_password_encoded = self::hashPassword($new_password);
537 $return['password'] = $new_password;
539 $keys = Crypto::newKeypair(4096);
540 if ($keys === false) {
541 throw new Exception(L10n::t('SERIOUS ERROR: Generation of security keys failed.'));
544 $prvkey = $keys['prvkey'];
545 $pubkey = $keys['pubkey'];
547 // Create another keypair for signing/verifying salmon protocol messages.
548 $sres = Crypto::newKeypair(512);
549 $sprvkey = $sres['prvkey'];
550 $spubkey = $sres['pubkey'];
552 $insert_result = DBA::insert('user', [
553 'guid' => System::createUUID(),
554 'username' => $username,
555 'password' => $new_password_encoded,
557 'openid' => $openid_url,
558 'nickname' => $nickname,
561 'spubkey' => $spubkey,
562 'sprvkey' => $sprvkey,
563 'verified' => $verified,
564 'blocked' => $blocked,
565 'language' => $language,
567 'register_date' => DateTimeFormat::utcNow(),
568 'default-location' => ''
571 if ($insert_result) {
572 $uid = DBA::lastInsertId();
573 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
575 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
579 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
582 // if somebody clicked submit twice very quickly, they could end up with two accounts
583 // due to race condition. Remove this one.
584 $user_count = DBA::count('user', ['nickname' => $nickname]);
585 if ($user_count > 1) {
586 DBA::delete('user', ['uid' => $uid]);
588 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
591 $insert_result = DBA::insert('profile', [
594 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
595 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
596 'publish' => $publish,
598 'net-publish' => $netpublish,
599 'profile-name' => L10n::t('default')
601 if (!$insert_result) {
602 DBA::delete('user', ['uid' => $uid]);
604 throw new Exception(L10n::t('An error occurred creating your default profile. Please try again.'));
607 // Create the self contact
608 if (!Contact::createSelfFromUserId($uid)) {
609 DBA::delete('user', ['uid' => $uid]);
611 throw new Exception(L10n::t('An error occurred creating your self contact. Please try again.'));
614 // Create a group with no members. This allows somebody to use it
615 // right away as a default group for new contacts.
616 $def_gid = Group::create($uid, L10n::t('Friends'));
618 DBA::delete('user', ['uid' => $uid]);
620 throw new Exception(L10n::t('An error occurred creating your default contact group. Please try again.'));
623 $fields = ['def_gid' => $def_gid];
624 if (Config::get('system', 'newuser_private') && $def_gid) {
625 $fields['allow_gid'] = '<' . $def_gid . '>';
628 DBA::update('user', $fields, ['uid' => $uid]);
630 // if we have no OpenID photo try to look up an avatar
631 if (!strlen($photo)) {
632 $photo = Network::lookupAvatarByEmail($email);
635 // unless there is no avatar-addon loaded
636 if (strlen($photo)) {
637 $photo_failure = false;
639 $filename = basename($photo);
640 $img_str = Network::fetchUrl($photo, true);
641 // guess mimetype from headers or filename
642 $type = Image::guessType($photo, true);
644 $Image = new Image($img_str, $type);
645 if ($Image->isValid()) {
646 $Image->scaleToSquare(300);
648 $hash = Photo::newResource();
650 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 4);
653 $photo_failure = true;
656 $Image->scaleDown(80);
658 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 5);
661 $photo_failure = true;
664 $Image->scaleDown(48);
666 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 6);
669 $photo_failure = true;
672 if (!$photo_failure) {
673 DBA::update('photo', ['profile' => 1], ['resource-id' => $hash]);
678 Addon::callHooks('register_account', $uid);
680 $return['user'] = $user;
685 * @brief Sends pending registration confirmation email
687 * @param array $user User record array
688 * @param string $sitename
689 * @param string $siteurl
690 * @param string $password Plaintext password
691 * @return NULL|boolean from notification() and email() inherited
693 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
695 $body = deindent(L10n::t('
697 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
699 Your login details are as follows:
705 $user['username'], $sitename, $siteurl, $user['nickname'], $password
708 return notification([
709 'type' => SYSTEM_EMAIL,
710 'uid' => $user['uid'],
711 'to_email' => $user['email'],
712 'subject' => L10n::t('Registration at %s', $sitename),
718 * @brief Sends registration confirmation
720 * It's here as a function because the mail is sent from different parts
722 * @param array $user User record array
723 * @param string $sitename
724 * @param string $siteurl
725 * @param string $password Plaintext password
726 * @return NULL|boolean from notification() and email() inherited
728 public static function sendRegisterOpenEmail($user, $sitename, $siteurl, $password)
730 $preamble = deindent(L10n::t('
732 Thank you for registering at %2$s. Your account has been created.
734 $preamble, $user['username'], $sitename
736 $body = deindent(L10n::t('
737 The login details are as follows:
743 You may change your password from your account "Settings" page after logging
746 Please take a few moments to review the other account settings on that page.
748 You may also wish to add some basic information to your default profile
749 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
751 We recommend setting your full name, adding a profile photo,
752 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
753 perhaps what country you live in; if you do not wish to be more specific
756 We fully respect your right to privacy, and none of these items are necessary.
757 If you are new and do not know anybody here, they may help
758 you to make some new and interesting friends.
760 If you ever want to delete your account, you can do so at %3$s/removeme
762 Thank you and welcome to %2$s.',
763 $user['email'], $sitename, $siteurl, $user['username'], $password
766 return notification([
767 'uid' => $user['uid'],
768 'language' => $user['language'],
769 'type' => SYSTEM_EMAIL,
770 'to_email' => $user['email'],
771 'subject' => L10n::t('Registration details for %s', $sitename),
772 'preamble' => $preamble,
778 * @param object $uid user to remove
781 public static function remove($uid)
789 Logger::log('Removing user: ' . $uid);
791 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
793 Addon::callHooks('remove_user', $user);
795 // save username (actually the nickname as it is guaranteed
796 // unique), so it cannot be re-registered in the future.
797 DBA::insert('userd', ['username' => $user['nickname']]);
799 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
800 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc(DateTimeFormat::utcNow() . " + 7 day")], ['uid' => $uid]);
801 Worker::add(PRIORITY_HIGH, "Notifier", "removeme", $uid);
803 // Send an update to the directory
804 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
805 Worker::add(PRIORITY_LOW, "Directory", $self['url']);
807 // Remove the user relevant data
808 Worker::add(PRIORITY_LOW, "RemoveUser", $uid);
810 if ($uid == local_user()) {
811 unset($_SESSION['authenticated']);
812 unset($_SESSION['uid']);
813 $a->internalRedirect();