4 * @file src/Model/User.php
5 * This file includes the User class with user related database functions
8 namespace Friendica\Model;
10 use DivineOmega\PasswordExposed;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBA;
21 use Friendica\Model\TwoFactor\AppSpecificPassword;
22 use Friendica\Object\Image;
23 use Friendica\Util\Crypto;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\Images;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
28 use Friendica\Worker\Delivery;
32 * This class handles User related functions
39 * PAGE_FLAGS_NORMAL is a typical personal profile account
40 * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
41 * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
42 * write access to wall and comments (no email and not included in page owner's ACL lists)
43 * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
47 const PAGE_FLAGS_NORMAL = 0;
48 const PAGE_FLAGS_SOAPBOX = 1;
49 const PAGE_FLAGS_COMMUNITY = 2;
50 const PAGE_FLAGS_FREELOVE = 3;
51 const PAGE_FLAGS_BLOG = 4;
52 const PAGE_FLAGS_PRVGROUP = 5;
60 * ACCOUNT_TYPE_PERSON - the account belongs to a person
61 * Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
63 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
64 * Associated page type: PAGE_FLAGS_SOAPBOX
66 * ACCOUNT_TYPE_NEWS - the account is a news reflector
67 * Associated page type: PAGE_FLAGS_SOAPBOX
69 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
70 * Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
72 * ACCOUNT_TYPE_RELAY - the account is a relay
73 * This will only be assigned to contacts, not to user accounts
76 const ACCOUNT_TYPE_PERSON = 0;
77 const ACCOUNT_TYPE_ORGANISATION = 1;
78 const ACCOUNT_TYPE_NEWS = 2;
79 const ACCOUNT_TYPE_COMMUNITY = 3;
80 const ACCOUNT_TYPE_RELAY = 4;
86 * Returns true if a user record exists with the provided id
92 public static function exists($uid)
94 return DBA::exists('user', ['uid' => $uid]);
99 * @param array $fields
100 * @return array|boolean User record if it exists, false otherwise
103 public static function getById($uid, array $fields = [])
105 return DBA::selectFirst('user', $fields, ['uid' => $uid]);
109 * Returns a user record based on it's GUID
111 * @param string $guid The guid of the user
112 * @param array $fields The fields to retrieve
113 * @param bool $active True, if only active records are searched
115 * @return array|boolean User record if it exists, false otherwise
118 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
121 $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
123 $cond = ['guid' => $guid];
126 return DBA::selectFirst('user', $fields, $cond);
130 * @param string $nickname
131 * @param array $fields
132 * @return array|boolean User record if it exists, false otherwise
135 public static function getByNickname($nickname, array $fields = [])
137 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
141 * Returns the user id of a given profile URL
145 * @return integer user id
148 public static function getIdForURL($url)
150 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => Strings::normaliseLink($url), 'self' => true]);
151 if (!DBA::isResult($self)) {
159 * Get a user based on its email
161 * @param string $email
162 * @param array $fields
164 * @return array|boolean User record if it exists, false otherwise
168 public static function getByEmail($email, array $fields = [])
170 return DBA::selectFirst('user', $fields, ['email' => $email]);
174 * Get owner data by user id
177 * @param boolean $check_valid Test if data is invalid and correct it
178 * @return boolean|array
181 public static function getOwnerDataById($uid, $check_valid = true)
183 $r = DBA::fetchFirst(
186 `user`.`prvkey` AS `uprvkey`,
192 `user`.`account-type`,
194 `user`.`account_removed`,
198 ON `user`.`uid` = `contact`.`uid`
199 WHERE `contact`.`uid` = ?
204 if (!DBA::isResult($r)) {
208 if (empty($r['nickname'])) {
216 // Check if the returned data is valid, otherwise fix it. See issue #6122
218 // Check for correct url and normalised nurl
219 $url = DI::baseUrl() . '/profile/' . $r['nickname'];
220 $repair = ($r['url'] != $url) || ($r['nurl'] != Strings::normaliseLink($r['url']));
223 // Check if "addr" is present and correct
224 $addr = $r['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
225 $repair = ($addr != $r['addr']);
229 // Check if the avatar field is filled and the photo directs to the correct path
230 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
231 if (DBA::isResult($avatar)) {
232 $repair = empty($r['avatar']) || !strpos($r['photo'], $avatar['resource-id']);
237 Contact::updateSelfFromUserID($uid);
238 // Return the corrected data and avoid a loop
239 $r = self::getOwnerDataById($uid, false);
246 * Get owner data by nick name
249 * @return boolean|array
252 public static function getOwnerDataByNick($nick)
254 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
256 if (!DBA::isResult($user)) {
260 return self::getOwnerDataById($user['uid']);
264 * Returns the default group for a given user and network
266 * @param int $uid User id
267 * @param string $network network name
269 * @return int group id
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 public static function getDefaultGroup($uid, $network = '')
276 if ($network == Protocol::OSTATUS) {
277 $default_group = DI::pConfig()->get($uid, "ostatus", "default_group");
280 if ($default_group != 0) {
281 return $default_group;
284 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
286 if (DBA::isResult($user)) {
287 $default_group = $user["def_gid"];
290 return $default_group;
295 * Authenticate a user with a clear text password
297 * @param mixed $user_info
298 * @param string $password
299 * @param bool $third_party
300 * @return int|boolean
301 * @deprecated since version 3.6
302 * @see User::getIdFromPasswordAuthentication()
304 public static function authenticate($user_info, $password, $third_party = false)
307 return self::getIdFromPasswordAuthentication($user_info, $password, $third_party);
308 } catch (Exception $ex) {
314 * Authenticate a user with a clear text password
316 * Returns the user id associated with a successful password authentication
318 * @param mixed $user_info
319 * @param string $password
320 * @param bool $third_party
321 * @return int User Id if authentication is successful
324 public static function getIdFromPasswordAuthentication($user_info, $password, $third_party = false)
326 $user = self::getAuthenticationInfo($user_info);
328 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
329 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
330 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
333 } elseif (strpos($user['password'], '$') === false) {
334 //Legacy hash that has not been replaced by a new hash yet
335 if (self::hashPasswordLegacy($password) === $user['password']) {
336 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
340 } elseif (!empty($user['legacy_password'])) {
341 //Legacy hash that has been double-hashed and not replaced by a new hash yet
342 //Warning: `legacy_password` is not necessary in sync with the content of `password`
343 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
344 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
348 } elseif (password_verify($password, $user['password'])) {
350 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
351 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
357 throw new Exception(DI::l10n()->t('Login failed'));
361 * Returns authentication info from various parameters types
363 * User info can be any of the following:
366 * - User email or username or nickname
367 * - User array with at least the uid and the hashed password
369 * @param mixed $user_info
373 private static function getAuthenticationInfo($user_info)
377 if (is_object($user_info) || is_array($user_info)) {
378 if (is_object($user_info)) {
379 $user = (array) $user_info;
386 || !isset($user['password'])
387 || !isset($user['legacy_password'])
389 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
391 } elseif (is_int($user_info) || is_string($user_info)) {
392 if (is_int($user_info)) {
393 $user = DBA::selectFirst(
395 ['uid', 'password', 'legacy_password'],
399 'account_expired' => 0,
400 'account_removed' => 0,
405 $fields = ['uid', 'password', 'legacy_password'];
407 "(`email` = ? OR `username` = ? OR `nickname` = ?)
408 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
409 $user_info, $user_info, $user_info
411 $user = DBA::selectFirst('user', $fields, $condition);
414 if (!DBA::isResult($user)) {
415 throw new Exception(DI::l10n()->t('User not found'));
423 * Generates a human-readable random password
427 public static function generateNewPassword()
429 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
433 * Checks if the provided plaintext password has been exposed or not
435 * @param string $password
439 public static function isPasswordExposed($password)
441 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
442 $cache->changeConfig([
443 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
447 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
449 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
450 } catch (\Exception $e) {
451 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
452 'code' => $e->getCode(),
453 'file' => $e->getFile(),
454 'line' => $e->getLine(),
455 'trace' => $e->getTraceAsString()
463 * Legacy hashing function, kept for password migration purposes
465 * @param string $password
468 private static function hashPasswordLegacy($password)
470 return hash('whirlpool', $password);
474 * Global user password hashing function
476 * @param string $password
480 public static function hashPassword($password)
482 if (!trim($password)) {
483 throw new Exception(DI::l10n()->t('Password can\'t be empty'));
486 return password_hash($password, PASSWORD_DEFAULT);
490 * Updates a user row with a new plaintext password
493 * @param string $password
497 public static function updatePassword($uid, $password)
499 $password = trim($password);
501 if (empty($password)) {
502 throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
505 if (!Config::get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
506 throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
509 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
511 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
512 throw new Exception(DI::l10n()->t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
515 return self::updatePasswordHashed($uid, self::hashPassword($password));
519 * Updates a user row with a new hashed password.
520 * Empties the password reset token field just in case.
523 * @param string $pasword_hashed
527 private static function updatePasswordHashed($uid, $pasword_hashed)
530 'password' => $pasword_hashed,
532 'pwdreset_time' => null,
533 'legacy_password' => false
535 return DBA::update('user', $fields, ['uid' => $uid]);
539 * Checks if a nickname is in the list of the forbidden nicknames
541 * Check if a nickname is forbidden from registration on the node by the
542 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
545 * @param string $nickname The nickname that should be checked
546 * @return boolean True is the nickname is blocked on the node
547 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
549 public static function isNicknameBlocked($nickname)
551 $forbidden_nicknames = Config::get('system', 'forbidden_nicknames', '');
553 // if the config variable is empty return false
554 if (empty($forbidden_nicknames)) {
558 // check if the nickname is in the list of blocked nicknames
559 $forbidden = explode(',', $forbidden_nicknames);
560 $forbidden = array_map('trim', $forbidden);
561 if (in_array(strtolower($nickname), $forbidden)) {
570 * Catch-all user creation function
572 * Creates a user from the provided data array, either form fields or OpenID.
573 * Required: { username, nickname, email } or { openid_url }
575 * Performs the following:
576 * - Sends to the OpenId auth URL (if relevant)
577 * - Creates new key pairs for crypto
578 * - Create self-contact
579 * - Create profile image
583 * @throws \ErrorException
584 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
585 * @throws \ImagickException
588 public static function create(array $data)
590 $return = ['user' => null, 'password' => ''];
592 $using_invites = Config::get('system', 'invitation_only');
594 $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
595 $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
596 $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
597 $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
598 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
599 $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
600 $password = !empty($data['password']) ? trim($data['password']) : '';
601 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
602 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
603 $blocked = !empty($data['blocked']);
604 $verified = !empty($data['verified']);
605 $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
607 $publish = !empty($data['profile_publish_reg']);
608 $netpublish = $publish && Config::get('system', 'directory');
610 if ($password1 != $confirm) {
611 throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
612 } elseif ($password1 != '') {
613 $password = $password1;
616 if ($using_invites) {
618 throw new Exception(DI::l10n()->t('An invitation is required.'));
621 if (!Register::existsByHash($invite_id)) {
622 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
626 /// @todo Check if this part is really needed. We should have fetched all this data in advance
627 if (empty($username) || empty($email) || empty($nickname)) {
629 if (!Network::isUrlValid($openid_url)) {
630 throw new Exception(DI::l10n()->t('Invalid OpenID url'));
632 $_SESSION['register'] = 1;
633 $_SESSION['openid'] = $openid_url;
635 $openid = new LightOpenID(DI::baseUrl()->getHostname());
636 $openid->identity = $openid_url;
637 $openid->returnUrl = DI::baseUrl() . '/openid';
638 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
639 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
641 $authurl = $openid->authUrl();
642 } catch (Exception $e) {
643 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);
645 System::externalRedirect($authurl);
649 throw new Exception(DI::l10n()->t('Please enter the required information.'));
652 if (!Network::isUrlValid($openid_url)) {
656 // collapse multiple spaces in name
657 $username = preg_replace('/ +/', ' ', $username);
659 $username_min_length = max(1, min(64, intval(Config::get('system', 'username_min_length', 3))));
660 $username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48))));
662 if ($username_min_length > $username_max_length) {
663 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);
664 $tmp = $username_min_length;
665 $username_min_length = $username_max_length;
666 $username_max_length = $tmp;
669 if (mb_strlen($username) < $username_min_length) {
670 throw new Exception(L10n::tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
673 if (mb_strlen($username) > $username_max_length) {
674 throw new Exception(L10n::tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
677 // So now we are just looking for a space in the full name.
678 $loose_reg = Config::get('system', 'no_regfullname');
680 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
681 if (strpos($username, ' ') === false) {
682 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
686 if (!Network::isEmailDomainAllowed($email)) {
687 throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
690 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
691 throw new Exception(DI::l10n()->t('Not a valid email address.'));
693 if (self::isNicknameBlocked($nickname)) {
694 throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
697 if (Config::get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
698 throw new Exception(DI::l10n()->t('Cannot use that email.'));
701 // Disallow somebody creating an account using openid that uses the admin email address,
702 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
703 if (Config::get('config', 'admin_email') && strlen($openid_url)) {
704 $adminlist = explode(',', str_replace(' ', '', strtolower(Config::get('config', 'admin_email'))));
705 if (in_array(strtolower($email), $adminlist)) {
706 throw new Exception(DI::l10n()->t('Cannot use that email.'));
710 $nickname = $data['nickname'] = strtolower($nickname);
712 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
713 throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
716 // Check existing and deleted accounts for this nickname.
718 DBA::exists('user', ['nickname' => $nickname])
719 || DBA::exists('userd', ['username' => $nickname])
721 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
724 $new_password = strlen($password) ? $password : User::generateNewPassword();
725 $new_password_encoded = self::hashPassword($new_password);
727 $return['password'] = $new_password;
729 $keys = Crypto::newKeypair(4096);
730 if ($keys === false) {
731 throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
734 $prvkey = $keys['prvkey'];
735 $pubkey = $keys['pubkey'];
737 // Create another keypair for signing/verifying salmon protocol messages.
738 $sres = Crypto::newKeypair(512);
739 $sprvkey = $sres['prvkey'];
740 $spubkey = $sres['pubkey'];
742 $insert_result = DBA::insert('user', [
743 'guid' => System::createUUID(),
744 'username' => $username,
745 'password' => $new_password_encoded,
747 'openid' => $openid_url,
748 'nickname' => $nickname,
751 'spubkey' => $spubkey,
752 'sprvkey' => $sprvkey,
753 'verified' => $verified,
754 'blocked' => $blocked,
755 'language' => $language,
757 'register_date' => DateTimeFormat::utcNow(),
758 'default-location' => ''
761 if ($insert_result) {
762 $uid = DBA::lastInsertId();
763 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
765 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
769 throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
772 // if somebody clicked submit twice very quickly, they could end up with two accounts
773 // due to race condition. Remove this one.
774 $user_count = DBA::count('user', ['nickname' => $nickname]);
775 if ($user_count > 1) {
776 DBA::delete('user', ['uid' => $uid]);
778 throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
781 $insert_result = DBA::insert('profile', [
784 'photo' => DI::baseUrl() . "/photo/profile/{$uid}.jpg",
785 'thumb' => DI::baseUrl() . "/photo/avatar/{$uid}.jpg",
786 'publish' => $publish,
788 'net-publish' => $netpublish,
789 'profile-name' => DI::l10n()->t('default')
791 if (!$insert_result) {
792 DBA::delete('user', ['uid' => $uid]);
794 throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
797 // Create the self contact
798 if (!Contact::createSelfFromUserId($uid)) {
799 DBA::delete('user', ['uid' => $uid]);
801 throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
804 // Create a group with no members. This allows somebody to use it
805 // right away as a default group for new contacts.
806 $def_gid = Group::create($uid, DI::l10n()->t('Friends'));
808 DBA::delete('user', ['uid' => $uid]);
810 throw new Exception(DI::l10n()->t('An error occurred creating your default contact group. Please try again.'));
813 $fields = ['def_gid' => $def_gid];
814 if (Config::get('system', 'newuser_private') && $def_gid) {
815 $fields['allow_gid'] = '<' . $def_gid . '>';
818 DBA::update('user', $fields, ['uid' => $uid]);
820 // if we have no OpenID photo try to look up an avatar
821 if (!strlen($photo)) {
822 $photo = Network::lookupAvatarByEmail($email);
825 // unless there is no avatar-addon loaded
826 if (strlen($photo)) {
827 $photo_failure = false;
829 $filename = basename($photo);
830 $img_str = Network::fetchUrl($photo, true);
831 // guess mimetype from headers or filename
832 $type = Images::guessType($photo, true);
834 $Image = new Image($img_str, $type);
835 if ($Image->isValid()) {
836 $Image->scaleToSquare(300);
838 $resource_id = Photo::newResource();
840 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 4);
843 $photo_failure = true;
846 $Image->scaleDown(80);
848 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 5);
851 $photo_failure = true;
854 $Image->scaleDown(48);
856 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 6);
859 $photo_failure = true;
862 if (!$photo_failure) {
863 Photo::update(['profile' => 1], ['resource-id' => $resource_id]);
868 Hook::callAll('register_account', $uid);
870 $return['user'] = $user;
875 * Sends pending registration confirmation email
877 * @param array $user User record array
878 * @param string $sitename
879 * @param string $siteurl
880 * @param string $password Plaintext password
881 * @return NULL|boolean from notification() and email() inherited
882 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
884 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
886 $body = Strings::deindent(DI::l10n()->t(
889 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
891 Your login details are as follows:
904 return notification([
905 'type' => SYSTEM_EMAIL,
906 'uid' => $user['uid'],
907 'to_email' => $user['email'],
908 'subject' => DI::l10n()->t('Registration at %s', $sitename),
914 * Sends registration confirmation
916 * It's here as a function because the mail is sent from different parts
918 * @param L10n\L10n $l10n The used language
919 * @param array $user User record array
920 * @param string $sitename
921 * @param string $siteurl
922 * @param string $password Plaintext password
923 * @return NULL|boolean from notification() and email() inherited
924 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
926 public static function sendRegisterOpenEmail(L10n\L10n $l10n, $user, $sitename, $siteurl, $password)
928 $preamble = Strings::deindent($l10n->t(
931 Thank you for registering at %2$s. Your account has been created.
936 $body = Strings::deindent($l10n->t(
938 The login details are as follows:
944 You may change your password from your account "Settings" page after logging
947 Please take a few moments to review the other account settings on that page.
949 You may also wish to add some basic information to your default profile
950 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
952 We recommend setting your full name, adding a profile photo,
953 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
954 perhaps what country you live in; if you do not wish to be more specific
957 We fully respect your right to privacy, and none of these items are necessary.
958 If you are new and do not know anybody here, they may help
959 you to make some new and interesting friends.
961 If you ever want to delete your account, you can do so at %3$s/removeme
963 Thank you and welcome to %2$s.',
971 return notification([
972 'uid' => $user['uid'],
973 'language' => $user['language'],
974 'type' => SYSTEM_EMAIL,
975 'to_email' => $user['email'],
976 'subject' => DI::l10n()->t('Registration details for %s', $sitename),
977 'preamble' => $preamble,
983 * @param object $uid user to remove
985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
987 public static function remove($uid)
993 Logger::log('Removing user: ' . $uid);
995 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
997 Hook::callAll('remove_user', $user);
999 // save username (actually the nickname as it is guaranteed
1000 // unique), so it cannot be re-registered in the future.
1001 DBA::insert('userd', ['username' => $user['nickname']]);
1003 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
1004 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1005 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1007 // Send an update to the directory
1008 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1009 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
1011 // Remove the user relevant data
1012 Worker::add(PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1018 * Return all identities to a user
1020 * @param int $uid The user id
1021 * @return array All identities for this user
1023 * Example for a return:
1027 * 'username' => 'maxmuster',
1028 * 'nickname' => 'Max Mustermann'
1032 * 'username' => 'johndoe',
1033 * 'nickname' => 'John Doe'
1038 public static function identities($uid)
1042 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1043 if (!DBA::isResult($user)) {
1047 if ($user['parent-uid'] == 0) {
1048 // First add our own entry
1050 'uid' => $user['uid'],
1051 'username' => $user['username'],
1052 'nickname' => $user['nickname']
1055 // Then add all the children
1058 ['uid', 'username', 'nickname'],
1059 ['parent-uid' => $user['uid'], 'account_removed' => false]
1061 if (DBA::isResult($r)) {
1062 $identities = array_merge($identities, DBA::toArray($r));
1065 // First entry is our parent
1068 ['uid', 'username', 'nickname'],
1069 ['uid' => $user['parent-uid'], 'account_removed' => false]
1071 if (DBA::isResult($r)) {
1072 $identities = DBA::toArray($r);
1075 // Then add all siblings
1078 ['uid', 'username', 'nickname'],
1079 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1081 if (DBA::isResult($r)) {
1082 $identities = array_merge($identities, DBA::toArray($r));
1087 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1089 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1090 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1093 if (DBA::isResult($r)) {
1094 $identities = array_merge($identities, DBA::toArray($r));
1101 * Returns statistical information about the current users of this node
1107 public static function getStatistics()
1111 'active_users_halfyear' => 0,
1112 'active_users_monthly' => 0,
1115 $userStmt = DBA::p("SELECT `user`.`uid`, `user`.`login_date`, `contact`.`last-item`
1117 INNER JOIN `profile` ON `profile`.`uid` = `user`.`uid` AND `profile`.`is-default`
1118 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
1119 WHERE (`profile`.`publish` OR `profile`.`net-publish`) AND `user`.`verified`
1120 AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1121 AND NOT `user`.`account_expired`");
1123 if (!DBA::isResult($userStmt)) {
1127 $halfyear = time() - (180 * 24 * 60 * 60);
1128 $month = time() - (30 * 24 * 60 * 60);
1130 while ($user = DBA::fetch($userStmt)) {
1131 $statistics['total_users']++;
1133 if ((strtotime($user['login_date']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1135 $statistics['active_users_halfyear']++;
1138 if ((strtotime($user['login_date']) > $month) || (strtotime($user['last-item']) > $month)
1140 $statistics['active_users_monthly']++;