4 * @file src/Model/User.php
5 * @brief 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\PConfig;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 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\Network;
26 use Friendica\Util\Strings;
27 use Friendica\Worker\Delivery;
31 * @brief This class handles User related functions
38 * PAGE_FLAGS_NORMAL is a typical personal profile account
39 * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
40 * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
41 * write access to wall and comments (no email and not included in page owner's ACL lists)
42 * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
46 const PAGE_FLAGS_NORMAL = 0;
47 const PAGE_FLAGS_SOAPBOX = 1;
48 const PAGE_FLAGS_COMMUNITY = 2;
49 const PAGE_FLAGS_FREELOVE = 3;
50 const PAGE_FLAGS_BLOG = 4;
51 const PAGE_FLAGS_PRVGROUP = 5;
59 * ACCOUNT_TYPE_PERSON - the account belongs to a person
60 * Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
62 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
63 * Associated page type: PAGE_FLAGS_SOAPBOX
65 * ACCOUNT_TYPE_NEWS - the account is a news reflector
66 * Associated page type: PAGE_FLAGS_SOAPBOX
68 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
69 * Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
71 * ACCOUNT_TYPE_RELAY - the account is a relay
72 * This will only be assigned to contacts, not to user accounts
75 const ACCOUNT_TYPE_PERSON = 0;
76 const ACCOUNT_TYPE_ORGANISATION = 1;
77 const ACCOUNT_TYPE_NEWS = 2;
78 const ACCOUNT_TYPE_COMMUNITY = 3;
79 const ACCOUNT_TYPE_RELAY = 4;
85 * Returns true if a user record exists with the provided id
91 public static function exists($uid)
93 return DBA::exists('user', ['uid' => $uid]);
98 * @param array $fields
99 * @return array|boolean User record if it exists, false otherwise
102 public static function getById($uid, array $fields = [])
104 return DBA::selectFirst('user', $fields, ['uid' => $uid]);
108 * Returns a user record based on it's GUID
110 * @param string $guid The guid of the user
111 * @param array $fields The fields to retrieve
112 * @param bool $active True, if only active records are searched
114 * @return array|boolean User record if it exists, false otherwise
117 public static function getByGuid(string $guid, array $fields = [], bool $active = true)
120 $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
122 $cond = ['guid' => $guid];
125 return DBA::selectFirst('user', $fields, $cond);
129 * @param string $nickname
130 * @param array $fields
131 * @return array|boolean User record if it exists, false otherwise
134 public static function getByNickname($nickname, array $fields = [])
136 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
140 * @brief Returns the user id of a given profile URL
144 * @return integer user id
147 public static function getIdForURL($url)
149 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => Strings::normaliseLink($url), 'self' => true]);
150 if (!DBA::isResult($self)) {
158 * Get a user based on its email
160 * @param string $email
161 * @param array $fields
163 * @return array|boolean User record if it exists, false otherwise
167 public static function getByEmail($email, array $fields = [])
169 return DBA::selectFirst('user', $fields, ['email' => $email]);
173 * @brief Get owner data by user id
176 * @param boolean $check_valid Test if data is invalid and correct it
177 * @return boolean|array
180 public static function getOwnerDataById($uid, $check_valid = true)
182 $r = DBA::fetchFirst(
185 `user`.`prvkey` AS `uprvkey`,
191 `user`.`account-type`,
193 `user`.`account_removed`
196 ON `user`.`uid` = `contact`.`uid`
197 WHERE `contact`.`uid` = ?
202 if (!DBA::isResult($r)) {
206 if (empty($r['nickname'])) {
214 // Check if the returned data is valid, otherwise fix it. See issue #6122
216 // Check for correct url and normalised nurl
217 $url = System::baseUrl() . '/profile/' . $r['nickname'];
218 $repair = ($r['url'] != $url) || ($r['nurl'] != Strings::normaliseLink($r['url']));
221 // Check if "addr" is present and correct
222 $addr = $r['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
223 $repair = ($addr != $r['addr']);
227 // Check if the avatar field is filled and the photo directs to the correct path
228 $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
229 if (DBA::isResult($avatar)) {
230 $repair = empty($r['avatar']) || !strpos($r['photo'], $avatar['resource-id']);
235 Contact::updateSelfFromUserID($uid);
236 // Return the corrected data and avoid a loop
237 $r = self::getOwnerDataById($uid, false);
244 * @brief Get owner data by nick name
247 * @return boolean|array
250 public static function getOwnerDataByNick($nick)
252 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
254 if (!DBA::isResult($user)) {
258 return self::getOwnerDataById($user['uid']);
262 * @brief Returns the default group for a given user and network
264 * @param int $uid User id
265 * @param string $network network name
267 * @return int group id
268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270 public static function getDefaultGroup($uid, $network = '')
274 if ($network == Protocol::OSTATUS) {
275 $default_group = PConfig::get($uid, "ostatus", "default_group");
278 if ($default_group != 0) {
279 return $default_group;
282 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
284 if (DBA::isResult($user)) {
285 $default_group = $user["def_gid"];
288 return $default_group;
293 * Authenticate a user with a clear text password
295 * @brief Authenticate a user with a clear text password
296 * @param mixed $user_info
297 * @param string $password
298 * @param bool $third_party
299 * @return int|boolean
300 * @deprecated since version 3.6
301 * @see User::getIdFromPasswordAuthentication()
303 public static function authenticate($user_info, $password, $third_party = false)
306 return self::getIdFromPasswordAuthentication($user_info, $password, $third_party);
307 } catch (Exception $ex) {
313 * Returns the user id associated with a successful password authentication
315 * @brief Authenticate a user with a clear text password
316 * @param mixed $user_info
317 * @param string $password
318 * @param bool $third_party
319 * @return int User Id if authentication is successful
322 public static function getIdFromPasswordAuthentication($user_info, $password, $third_party = false)
324 $user = self::getAuthenticationInfo($user_info);
326 if ($third_party && PConfig::get($user['uid'], '2fa', 'verified')) {
327 // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
328 if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
331 } elseif (strpos($user['password'], '$') === false) {
332 //Legacy hash that has not been replaced by a new hash yet
333 if (self::hashPasswordLegacy($password) === $user['password']) {
334 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
338 } elseif (!empty($user['legacy_password'])) {
339 //Legacy hash that has been double-hashed and not replaced by a new hash yet
340 //Warning: `legacy_password` is not necessary in sync with the content of `password`
341 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
342 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
346 } elseif (password_verify($password, $user['password'])) {
348 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
349 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
355 throw new Exception(L10n::t('Login failed'));
359 * Returns authentication info from various parameters types
361 * User info can be any of the following:
364 * - User email or username or nickname
365 * - User array with at least the uid and the hashed password
367 * @param mixed $user_info
371 private static function getAuthenticationInfo($user_info)
375 if (is_object($user_info) || is_array($user_info)) {
376 if (is_object($user_info)) {
377 $user = (array) $user_info;
384 || !isset($user['password'])
385 || !isset($user['legacy_password'])
387 throw new Exception(L10n::t('Not enough information to authenticate'));
389 } elseif (is_int($user_info) || is_string($user_info)) {
390 if (is_int($user_info)) {
391 $user = DBA::selectFirst(
393 ['uid', 'password', 'legacy_password'],
397 'account_expired' => 0,
398 'account_removed' => 0,
403 $fields = ['uid', 'password', 'legacy_password'];
405 "(`email` = ? OR `username` = ? OR `nickname` = ?)
406 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
407 $user_info, $user_info, $user_info
409 $user = DBA::selectFirst('user', $fields, $condition);
412 if (!DBA::isResult($user)) {
413 throw new Exception(L10n::t('User not found'));
421 * Generates a human-readable random password
425 public static function generateNewPassword()
427 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
431 * Checks if the provided plaintext password has been exposed or not
433 * @param string $password
437 public static function isPasswordExposed($password)
439 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
440 $cache->changeConfig([
441 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
445 $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
447 return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
448 } catch (\Exception $e) {
449 Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
450 'code' => $e->getCode(),
451 'file' => $e->getFile(),
452 'line' => $e->getLine(),
453 'trace' => $e->getTraceAsString()
461 * Legacy hashing function, kept for password migration purposes
463 * @param string $password
466 private static function hashPasswordLegacy($password)
468 return hash('whirlpool', $password);
472 * Global user password hashing function
474 * @param string $password
478 public static function hashPassword($password)
480 if (!trim($password)) {
481 throw new Exception(L10n::t('Password can\'t be empty'));
484 return password_hash($password, PASSWORD_DEFAULT);
488 * Updates a user row with a new plaintext password
491 * @param string $password
495 public static function updatePassword($uid, $password)
497 $password = trim($password);
499 if (empty($password)) {
500 throw new Exception(L10n::t('Empty passwords are not allowed.'));
503 if (!Config::get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
504 throw new Exception(L10n::t('The new password has been exposed in a public data dump, please choose another.'));
507 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
509 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
510 throw new Exception(L10n::t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
513 return self::updatePasswordHashed($uid, self::hashPassword($password));
517 * Updates a user row with a new hashed password.
518 * Empties the password reset token field just in case.
521 * @param string $pasword_hashed
525 private static function updatePasswordHashed($uid, $pasword_hashed)
528 'password' => $pasword_hashed,
530 'pwdreset_time' => null,
531 'legacy_password' => false
533 return DBA::update('user', $fields, ['uid' => $uid]);
537 * @brief Checks if a nickname is in the list of the forbidden nicknames
539 * Check if a nickname is forbidden from registration on the node by the
540 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
543 * @param string $nickname The nickname that should be checked
544 * @return boolean True is the nickname is blocked on the node
545 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
547 public static function isNicknameBlocked($nickname)
549 $forbidden_nicknames = Config::get('system', 'forbidden_nicknames', '');
551 // if the config variable is empty return false
552 if (empty($forbidden_nicknames)) {
556 // check if the nickname is in the list of blocked nicknames
557 $forbidden = explode(',', $forbidden_nicknames);
558 $forbidden = array_map('trim', $forbidden);
559 if (in_array(strtolower($nickname), $forbidden)) {
568 * @brief Catch-all user creation function
570 * Creates a user from the provided data array, either form fields or OpenID.
571 * Required: { username, nickname, email } or { openid_url }
573 * Performs the following:
574 * - Sends to the OpenId auth URL (if relevant)
575 * - Creates new key pairs for crypto
576 * - Create self-contact
577 * - Create profile image
581 * @throws \ErrorException
582 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
583 * @throws \ImagickException
586 public static function create(array $data)
589 $return = ['user' => null, 'password' => ''];
591 $using_invites = Config::get('system', 'invitation_only');
593 $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
594 $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
595 $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
596 $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
597 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
598 $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
599 $password = !empty($data['password']) ? trim($data['password']) : '';
600 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
601 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
602 $blocked = !empty($data['blocked']);
603 $verified = !empty($data['verified']);
604 $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
606 $publish = !empty($data['profile_publish_reg']);
607 $netpublish = $publish && Config::get('system', 'directory');
609 if ($password1 != $confirm) {
610 throw new Exception(L10n::t('Passwords do not match. Password unchanged.'));
611 } elseif ($password1 != '') {
612 $password = $password1;
615 if ($using_invites) {
617 throw new Exception(L10n::t('An invitation is required.'));
620 if (!Register::existsByHash($invite_id)) {
621 throw new Exception(L10n::t('Invitation could not be verified.'));
625 if (empty($username) || empty($email) || empty($nickname)) {
627 if (!Network::isUrlValid($openid_url)) {
628 throw new Exception(L10n::t('Invalid OpenID url'));
630 $_SESSION['register'] = 1;
631 $_SESSION['openid'] = $openid_url;
633 $openid = new LightOpenID($a->getHostName());
634 $openid->identity = $openid_url;
635 $openid->returnUrl = System::baseUrl() . '/openid';
636 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
637 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
639 $authurl = $openid->authUrl();
640 } catch (Exception $e) {
641 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);
643 System::externalRedirect($authurl);
647 throw new Exception(L10n::t('Please enter the required information.'));
650 if (!Network::isUrlValid($openid_url)) {
654 // collapse multiple spaces in name
655 $username = preg_replace('/ +/', ' ', $username);
657 $username_min_length = max(1, min(64, intval(Config::get('system', 'username_min_length', 3))));
658 $username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48))));
660 if ($username_min_length > $username_max_length) {
661 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);
662 $tmp = $username_min_length;
663 $username_min_length = $username_max_length;
664 $username_max_length = $tmp;
667 if (mb_strlen($username) < $username_min_length) {
668 throw new Exception(L10n::tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
671 if (mb_strlen($username) > $username_max_length) {
672 throw new Exception(L10n::tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
675 // So now we are just looking for a space in the full name.
676 $loose_reg = Config::get('system', 'no_regfullname');
678 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
679 if (strpos($username, ' ') === false) {
680 throw new Exception(L10n::t("That doesn't appear to be your full (First Last) name."));
684 if (!Network::isEmailDomainAllowed($email)) {
685 throw new Exception(L10n::t('Your email domain is not among those allowed on this site.'));
688 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
689 throw new Exception(L10n::t('Not a valid email address.'));
691 if (self::isNicknameBlocked($nickname)) {
692 throw new Exception(L10n::t('The nickname was blocked from registration by the nodes admin.'));
695 if (Config::get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
696 throw new Exception(L10n::t('Cannot use that email.'));
699 // Disallow somebody creating an account using openid that uses the admin email address,
700 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
701 if (Config::get('config', 'admin_email') && strlen($openid_url)) {
702 $adminlist = explode(',', str_replace(' ', '', strtolower(Config::get('config', 'admin_email'))));
703 if (in_array(strtolower($email), $adminlist)) {
704 throw new Exception(L10n::t('Cannot use that email.'));
708 $nickname = $data['nickname'] = strtolower($nickname);
710 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
711 throw new Exception(L10n::t('Your nickname can only contain a-z, 0-9 and _.'));
714 // Check existing and deleted accounts for this nickname.
716 DBA::exists('user', ['nickname' => $nickname])
717 || DBA::exists('userd', ['username' => $nickname])
719 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
722 $new_password = strlen($password) ? $password : User::generateNewPassword();
723 $new_password_encoded = self::hashPassword($new_password);
725 $return['password'] = $new_password;
727 $keys = Crypto::newKeypair(4096);
728 if ($keys === false) {
729 throw new Exception(L10n::t('SERIOUS ERROR: Generation of security keys failed.'));
732 $prvkey = $keys['prvkey'];
733 $pubkey = $keys['pubkey'];
735 // Create another keypair for signing/verifying salmon protocol messages.
736 $sres = Crypto::newKeypair(512);
737 $sprvkey = $sres['prvkey'];
738 $spubkey = $sres['pubkey'];
740 $insert_result = DBA::insert('user', [
741 'guid' => System::createUUID(),
742 'username' => $username,
743 'password' => $new_password_encoded,
745 'openid' => $openid_url,
746 'nickname' => $nickname,
749 'spubkey' => $spubkey,
750 'sprvkey' => $sprvkey,
751 'verified' => $verified,
752 'blocked' => $blocked,
753 'language' => $language,
755 'register_date' => DateTimeFormat::utcNow(),
756 'default-location' => ''
759 if ($insert_result) {
760 $uid = DBA::lastInsertId();
761 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
763 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
767 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
770 // if somebody clicked submit twice very quickly, they could end up with two accounts
771 // due to race condition. Remove this one.
772 $user_count = DBA::count('user', ['nickname' => $nickname]);
773 if ($user_count > 1) {
774 DBA::delete('user', ['uid' => $uid]);
776 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
779 $insert_result = DBA::insert('profile', [
782 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
783 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
784 'publish' => $publish,
786 'net-publish' => $netpublish,
787 'profile-name' => L10n::t('default')
789 if (!$insert_result) {
790 DBA::delete('user', ['uid' => $uid]);
792 throw new Exception(L10n::t('An error occurred creating your default profile. Please try again.'));
795 // Create the self contact
796 if (!Contact::createSelfFromUserId($uid)) {
797 DBA::delete('user', ['uid' => $uid]);
799 throw new Exception(L10n::t('An error occurred creating your self contact. Please try again.'));
802 // Create a group with no members. This allows somebody to use it
803 // right away as a default group for new contacts.
804 $def_gid = Group::create($uid, L10n::t('Friends'));
806 DBA::delete('user', ['uid' => $uid]);
808 throw new Exception(L10n::t('An error occurred creating your default contact group. Please try again.'));
811 $fields = ['def_gid' => $def_gid];
812 if (Config::get('system', 'newuser_private') && $def_gid) {
813 $fields['allow_gid'] = '<' . $def_gid . '>';
816 DBA::update('user', $fields, ['uid' => $uid]);
818 // if we have no OpenID photo try to look up an avatar
819 if (!strlen($photo)) {
820 $photo = Network::lookupAvatarByEmail($email);
823 // unless there is no avatar-addon loaded
824 if (strlen($photo)) {
825 $photo_failure = false;
827 $filename = basename($photo);
828 $img_str = Network::fetchUrl($photo, true);
829 // guess mimetype from headers or filename
830 $type = Image::guessType($photo, true);
832 $Image = new Image($img_str, $type);
833 if ($Image->isValid()) {
834 $Image->scaleToSquare(300);
836 $hash = Photo::newResource();
838 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 4);
841 $photo_failure = true;
844 $Image->scaleDown(80);
846 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 5);
849 $photo_failure = true;
852 $Image->scaleDown(48);
854 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 6);
857 $photo_failure = true;
860 if (!$photo_failure) {
861 Photo::update(['profile' => 1], ['resource-id' => $hash]);
866 Hook::callAll('register_account', $uid);
868 $return['user'] = $user;
873 * @brief Sends pending registration confirmation email
875 * @param array $user User record array
876 * @param string $sitename
877 * @param string $siteurl
878 * @param string $password Plaintext password
879 * @return NULL|boolean from notification() and email() inherited
880 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
882 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
884 $body = Strings::deindent(L10n::t(
887 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
889 Your login details are as follows:
902 return notification([
903 'type' => SYSTEM_EMAIL,
904 'uid' => $user['uid'],
905 'to_email' => $user['email'],
906 'subject' => L10n::t('Registration at %s', $sitename),
912 * @brief Sends registration confirmation
914 * It's here as a function because the mail is sent from different parts
916 * @param array $user User record array
917 * @param string $sitename
918 * @param string $siteurl
919 * @param string $password Plaintext password
920 * @return NULL|boolean from notification() and email() inherited
921 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
923 public static function sendRegisterOpenEmail($user, $sitename, $siteurl, $password)
925 $preamble = Strings::deindent(L10n::t(
928 Thank you for registering at %2$s. Your account has been created.
933 $body = Strings::deindent(L10n::t(
935 The login details are as follows:
941 You may change your password from your account "Settings" page after logging
944 Please take a few moments to review the other account settings on that page.
946 You may also wish to add some basic information to your default profile
947 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
949 We recommend setting your full name, adding a profile photo,
950 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
951 perhaps what country you live in; if you do not wish to be more specific
954 We fully respect your right to privacy, and none of these items are necessary.
955 If you are new and do not know anybody here, they may help
956 you to make some new and interesting friends.
958 If you ever want to delete your account, you can do so at %3$s/removeme
960 Thank you and welcome to %2$s.',
968 return notification([
969 'uid' => $user['uid'],
970 'language' => $user['language'],
971 'type' => SYSTEM_EMAIL,
972 'to_email' => $user['email'],
973 'subject' => L10n::t('Registration details for %s', $sitename),
974 'preamble' => $preamble,
980 * @param object $uid user to remove
982 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
984 public static function remove($uid)
990 Logger::log('Removing user: ' . $uid);
992 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
994 Hook::callAll('remove_user', $user);
996 // save username (actually the nickname as it is guaranteed
997 // unique), so it cannot be re-registered in the future.
998 DBA::insert('userd', ['username' => $user['nickname']]);
1000 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
1001 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1002 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1004 // Send an update to the directory
1005 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1006 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
1008 // Remove the user relevant data
1009 Worker::add(PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1015 * Return all identities to a user
1017 * @param int $uid The user id
1018 * @return array All identities for this user
1020 * Example for a return:
1024 * 'username' => 'maxmuster',
1025 * 'nickname' => 'Max Mustermann'
1029 * 'username' => 'johndoe',
1030 * 'nickname' => 'John Doe'
1035 public static function identities($uid)
1039 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1040 if (!DBA::isResult($user)) {
1044 if ($user['parent-uid'] == 0) {
1045 // First add our own entry
1047 'uid' => $user['uid'],
1048 'username' => $user['username'],
1049 'nickname' => $user['nickname']
1052 // Then add all the children
1055 ['uid', 'username', 'nickname'],
1056 ['parent-uid' => $user['uid'], 'account_removed' => false]
1058 if (DBA::isResult($r)) {
1059 $identities = array_merge($identities, DBA::toArray($r));
1062 // First entry is our parent
1065 ['uid', 'username', 'nickname'],
1066 ['uid' => $user['parent-uid'], 'account_removed' => false]
1068 if (DBA::isResult($r)) {
1069 $identities = DBA::toArray($r);
1072 // Then add all siblings
1075 ['uid', 'username', 'nickname'],
1076 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1078 if (DBA::isResult($r)) {
1079 $identities = array_merge($identities, DBA::toArray($r));
1084 "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1086 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1087 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1090 if (DBA::isResult($r)) {
1091 $identities = array_merge($identities, DBA::toArray($r));
1098 * Returns statistical information about the current users of this node
1104 public static function getStatistics()
1108 'active_users_halfyear' => 0,
1109 'active_users_monthly' => 0,
1112 $userStmt = DBA::p("SELECT `user`.`uid`, `user`.`login_date`, `contact`.`last-item`
1114 INNER JOIN `profile` ON `profile`.`uid` = `user`.`uid` AND `profile`.`is-default`
1115 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
1116 WHERE (`profile`.`publish` OR `profile`.`net-publish`) AND `user`.`verified`
1117 AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1118 AND NOT `user`.`account_expired`");
1120 if (!DBA::isResult($userStmt)) {
1124 $halfyear = time() - (180 * 24 * 60 * 60);
1125 $month = time() - (30 * 24 * 60 * 60);
1127 while ($user = DBA::fetch($userStmt)) {
1128 $statistics['total_users']++;
1130 if ((strtotime($user['login_date']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1132 $statistics['active_users_halfyear']++;
1135 if ((strtotime($user['login_date']) > $month) || (strtotime($user['last-item']) > $month)
1137 $statistics['active_users_monthly']++;